#include <sys/socket.h>
#include <netdb.h> //hostent , gethostbyname gethostbyaddr
#include <string.h>//memcpy
#include <netinet/in.h>
#include <arpa/inet.h> //inet_ntop
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
int main(void)
{
unsigned long d;
struct in_addr addr;
char *ip = "192.168.1.11";
d = inet_addr(ip);
memcpy(&addr,&d, 4);//虽然说inet_addr与inet_ntoa互为反函数,但用inet_addr得到的值却不能直接用于inet_ntoa,需要用此方法转换成in_addr类型
printf("long format: %lu\n", d);
printf("convert to str: %s\n", inet_ntoa(addr));
char host[32]={0};
gethostname(host, sizeof(host));
printf("host name is: %s\n", host);
char *bd = "www.baidu.com";
struct hostent *hbd;
//gethostbyname,通过域名得到IP地址,此函数返回一个hostent结构指针,需要进一步转换才能用
hbd = gethostbyname(bd);
//直接打出来h_addr_list中有乱码,这个不能直接打,需要用下面的inet_ntop来转
printf("after gethostbyname: %s, %s, %d, %d, %s\n", hbd->h_name, *hbd->h_aliases,hbd->h_addrtype, hbd->h_length, *hbd->h_addr_list);
char ipbd[32]={0};
inet_ntop(hbd->h_addrtype, *hbd->h_addr_list,ipbd, sizeof(ipbd));
printf("real IP is: %s\n", ipbd);
return 0;
}
socket地址解析相关的几个函数inet_addr,inet_ntoa,gethostname,gethostbyname
最新推荐文章于 2023-03-15 00:00:32 发布