用tcp/IP进行网际互联-套接字API
时间:2010-12-31 来源:linyilong
代码
1 #include <iostream>代码
2 #include <netdb.h>
3 #include <sys/socket.h>
4 #include <unistd.h>
5
6 using namespace std;
7
8 int main(void)
9 {
10 struct protoent *ptr;
11
12 if(ptr=getprotobyname("udp"))
13 {
14 char **pptr=ptr->p_aliases;
15 cout<<ptr->p_name<<endl;
16
17 while(*pptr != NULL)
18 {
19 cout<<*pptr<<endl;
20 pptr++;
21 }
22 cout<<ptr->p_proto<<endl;
23 }
24 else
25 {
26 cout<<"error"<<endl;
27 }
28 }
1 #include <iostream>
2 #include <unistd.h>
3 #include <sys/types.h>
4 #include <netdb.h>
5 #include <sys/socket.h>
6 #include <arpa/inet.h>
7 #include <cstdlib>
8
9 using namespace std;
10 int main(void)
11 {
12 struct hostent *hptr;
13 char str[20];
14 gethostname(str,sizeof(str));
15 if(hptr=gethostbyname(str))
16 {
17 cout<<hptr->h_name<<endl;
18 switch(hptr->h_addrtype)
19 {
20 case AF_INET:
21 cout<<"AF_INET"<<endl;
22 break;
23 case AF_INET6:
24 cout<<"AF_INET6"<<endl;
25 break;
26 default:
27 cout<<"else"<<endl;
28 break;
29 }
30 char **ptr=hptr->h_aliases;
31
32 while(*ptr != NULL)
33 {
34 cout<<*ptr<<endl;
35 ptr++;
36 }
37
38 ptr=hptr->h_addr_list;
39 char str[32];
40
41 while(*ptr != NULL)
42 {
43 cout<<inet_ntop(hptr->h_addrtype,*ptr,str,sizeof(str));
44 ptr++;
45 }
46 cout<<hptr->h_length<<endl;
47 }
48 else
49 {
50 cout<<"error"<<endl;
51 }
52 }
53
代码
1 #include <iostream>
2 #include <netdb.h>
3 #include <unistd.h>
4 #include <sys/socket.h>
5 #include <errno.h>
6
7 using namespace std;
8
9 int main(void)
10 {
11 struct servent *ser_info;
12
13 if(ser_info=getservbyname("echo","udp"))
14 {
15 char **ptr;
16 cout<<ser_info->s_name<<endl;
17 ptr=ser_info->s_aliases;
18 while(*ptr != NULL)
19 {
20 cout<<*ptr<<endl;
21 ptr++;
22 }
23 cout<<(ser_info->s_port)<<endl;
24 cout<<ser_info->s_proto<<endl;
25 }
26 else
27 {
28 perror("getservbyname:");
29 }
30 }
31
相关阅读 更多 +