您的位置:首页 > 编程语言

UNIX环境编程------Unix编程实例------Gethostbyname和gethostname结合使用打印出主机IP地址

2015-11-26 11:11 801 查看
Gethostbyname和gethostname结合使用打印出主机IP地址:

源代码:

#include<unistd.h>

#include<netinet/in.h>

#include<sys/socket.h>

#include<stdio.h>

#include<errno.h>

#include<netdb.h>

#include<stdlib.h>

int main()

{

charname [50];

intgethnrvl;

inti=0;

struct hostent* hostent_t;

gethnrvl=gethostname(name,sizeof(name));

if(gethnrvl==-1)

{

perror("gethostnameerror");

_exit(-1);

}

printf("%s \n",name);

//使用gethostbyname获取 主机IP

hostent_t =gethostbyname(name);

//打印出IP地址

for(;hostent_t->h_addr_list[i];i++)

{

printf("%s/t",inet_ntoa(*(struct in_addr*)(hostent_t->h_addr_list[i])));

}

}

运行结果:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: