linux下的C socket编程(2)
获取域名对应的ip地址
经过上面的讨论,如果我们要向链接远程的服务器,我们需要知道对方的ip地址,系统函数gethostbyname便能够帮助我们实现这个目的。他能够获取域名对应的ip地址并且返回一个hostent类型的结果。其中包含了ip地址信息,它的头文件是:netdb.h
|
1
2
3
4
5
6
7
8
|
struct hostent{char * h_name;//主机名char **h_aliases;//别名列表int h_addrtype;//地址类型int h_length;//地址的长度char **h_addr_list;//地址列表} |
其中h_addr_list便是存放ip地址的信息。
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
|
#include<stdio.h>#include<string.h>#include<stdlib.h>#include<sys/socket.h>#include<sys/types.h>#include<netdb.h>int main(){char *hostname="www.baiidu.com";char ip[100];struct hostent *host;struct in_addr ** addr_list;int i;if(NULL==(host = gethostbyname(hostname))){perror("get host by name error\n");exit(1);}addr_list= (strut in_addr **)host->h_addr_list;for(i=0;addr_list[1]!=NULL;i+=1){//inet_ntoa()将long类型的ip地址转化成圆点字符串形式,作用与inet_addr()相反strcpy(ip,inet_ntoa(*addr_list[i])); }printf("%s resolved to %s ",hostname,ip);return 0;} |
gethostbuname()用来获取域名对应的ip地址,可以参加gethostbyname()来产看更多的用法。
从socket连接中获取对方ip:
由前面能够知道accept()返回的是结构体sockaddr_in,由此很容易得知对方的ip和端口信息。
|
1
2
|
char * client_ip = inet_ntoa(client.sin_addr);int cilent_port = ntohs(client.sin_port); |
到现在为止,我们已经解除了很多个重要类型。
1、sockaddr_in 连接信息
2、in_addr long 类型的ip地址。
3、sockaddr与sockaddr_in 类似,是通过用socket连接信息。
4、hostent 域名对应的ip信息。用在gethostbyname。