getbyhostname() 如何工作?
我正在编写一个基本的 UDP 客户端-服务器程序,但没有从 getbyhostname() 获得预期结果。这是我的代码片段:
char *clientHostName = malloc(HOST_NAME_MAX);
gethostname(clientHostName, HOST_NAME_MAX);
printf("%s\n",clientHostName);
struct hostent thehost = gethostbyname(clientHostName);
printf("%ld\n",(*((unsigned long *) thehost->h_addr_list[0])));
因此,第一个打印语句输出了我所期望的,即我的计算机的名称。但是,我希望第二条打印语句打印出我的 IP 地址。但不,它打印出这样的内容:4398250634。它打印出的是什么?如何获取我的 IP 地址?
I am writing a basic UDP Client-Server program and wasn't getting the expected results from getbyhostname(). Here is a snippet from my code:
char *clientHostName = malloc(HOST_NAME_MAX);
gethostname(clientHostName, HOST_NAME_MAX);
printf("%s\n",clientHostName);
struct hostent thehost = gethostbyname(clientHostName);
printf("%ld\n",(*((unsigned long *) thehost->h_addr_list[0])));
So, the first print statement outputs what I expected, the name of my computer. However, I expect the second print statement to print out my IP Address. But no, it print out something like this: 4398250634. What is this that it is printing out? How do I get my IP Address?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
首先,您不应该使用
gethostbyname
接口。它已被弃用,并且无法处理 IPv6,而 IPv6 在 2012 年是一个现实、实用的阻碍。正确使用的接口是getaddrinfo
。使用getaddrinfo
查找主机名并将其采用套接字地址形式后,您可以使用getnameinfo
和NI_NUMERICHOST
标志进行转换将其转换为可打印的 IP 地址形式。这适用于 IPv4 或 IPv6,或任何未来的协议。至于您的特定打印问题,您希望
%ld
如何打印 IP 地址?它以十进制(基数 10)打印单个数字(long
)。您可以将指针强制转换为unsigned char *
并读取 4 个元素,每个元素都用%d
打印,但这又是一个不好的方法。First of all, you should not be using the
gethostbyname
interface. It's deprecated and cannot deal with IPv6, which is a real-world, practical show-stopper in 2012. The proper interface to use isgetaddrinfo
. Once you've usedgetaddrinfo
to lookup a hostname and have it in a socket address form, you can usegetnameinfo
with theNI_NUMERICHOST
flag to convert it to a printable IP-address form. This works for either IPv4 or IPv6, or for any future protocols.As for your particular printing issue, how do you expect
%ld
to print an IP address? It prints a single number (long
) in decimal (base 10). You could instead cast the pointer tounsigned char *
and read 4 elements, each to be printed with%d
, but again this is a bad approach.您调用的函数和您正在检查的字段为您提供一个 32 位变量,每个 8 位八位字节包含您的 IP 地址的一段。以下代码:
在我的 Xubuntu 盒子上给出:
并且,如果您将末尾的十六进制数字分解为
01
、01
、00
和7f
,这是(由于我的 CPU,顺序相反)127.0.1.1
,环回地址之一。The functions you're calling, and the field you're examining, give you a 32-bit variable with each 8-bit octet containing on segment of your IP address. The following code:
on my Xubuntu box gives:
and, if you break down that hex number at the end into
01
,01
,00
and7f
, that's (in reverse order due to my CPU)127.0.1.1
, one of the loopback addresses.