[英]Getting the ip address of my machine in dotted decimal with C?
I'm trying to get a string with the ip address in dotted decimal of my machine.我正在尝试获取一个带有我机器的点分十进制 IP 地址的字符串。 What I do is trying to get the string from INADDR_LOOPBACK
with the following code.我所做的是尝试使用以下代码从INADDR_LOOPBACK
获取字符串。
char addr[INET_ADDRSTRLEN];
struct in_addr *in_addr1 = malloc(sizeof(struct in_addr));
in_addr1->s_addr = INADDR_LOOPBACK;
inet_ntop(AF_INET, in_addr1, addr, INET_ADDRSTRLEN);
printf("addr: %s\n", addr);
Here's what I get from the printf
:这是我从printf
得到的:
1.0.0.127 1.0.0.127
127.0.0.1
?它应该打印127.0.0.1
吗?$ ifconfig
... not the localhost!老实说,我期待获得我将要调用的 IP,例如$ ifconfig
... 不是本地主机! Did I misunderstand what INADDR_LOOBACK
does?我是否误解了INADDR_LOOBACK
作用?INADDR_LOOPBACK
is in host byte order , ie 0x7f000001
. INADDR_LOOPBACK
是主机字节顺序,即0x7f000001
。 It is, incidentally, the IPv4 address 127.0.0.1
.顺便说一下,它是 IPv4 地址127.0.0.1
。
in_addr1->s_addr
must be in network byte order . in_addr1->s_addr
必须是网络字节顺序。
Your computer is a little-endian computer where the host byte order doesn't match the network byte order.您的计算机是小端计算机,其中主机字节顺序与网络字节顺序不匹配。 You must use htonl
to convert the loopback address to network byte order.您必须使用htonl
将环回地址转换为网络字节顺序。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.