使用gethostname()得到主机名

转自:http://hi.baidu.com/jakisou/blog/item/3e74d611b3573711b8127bd7.html


int gethostname(char *name, size_t len)

 

这个函数,调用后,会将主机名保存在name里面。而len是name的大小。
windows、linux系统下都适用。

 

以下是例程,编译后只需要运行就知道自己的主机名字了。知道自己名字后,我再调用了一下gethostbyname()来得到主机的一些其他信息。

#include <netdb.h>
#include <sys/socket.h>

int main(int argc, char **argv)
{
struct hostent *hptr;
char **pptr;
char hostname[32];
char str[32];

if( gethostname(hostname,sizeof(hostname)) )
{
    printf("gethostname calling error/n");
    return 1;
}
printf("localhost name:%s/n",hostname);
if( (hptr = gethostbyname(hostname)) == NULL)
{
    printf("gethostbyname calling error/n");
    return 1;
}
pptr=hptr->h_addr_list;
for(;*pptr!=NULL;pptr++)
    printf("    address:%s/n", inet_ntop(hptr->h_addrtype, *pptr, str, sizeof(str)));

return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值