linux c 通过hostname获得ip地址

代码


#include <stdio.h>
#include <netdb.h>
int main()
{
        struct hostent *he;
        char hostname[40]={0} ;
        char ipaddr[40]={0};


        gethostname(hostname,sizeof(hostname));
        he = gethostbyname(hostname);
        printf("%d-handle-gethostbyname\n",he);
        printf("hostname=%s\n",hostname);
        //printf("%s\n",inet_ntoa(*(struct in_addr*)(he->h_addr)));
	char destIP[128];
	char **phe = NULL;
	for( phe=he->h_addr_list ; NULL != *phe ; ++phe)
	{
		inet_ntop(he->h_addrtype,*phe,destIP,sizeof(destIP));
		printf("addr:%s\n",destIP);
    
	}
}




编译
 gcc -o gh gh.c
执行
[root@mon1 ~]# ./gh
1836408896-handle-gethostbyname
hostname=xxx.yyy.net
addr:127.0.0.1
相关推荐
©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页