如何在 Linux 上用 C 语言获取我的 IP 地址?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20800319/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I get my IP address in C on Linux?
提问by Jelly
How could I get my IP address (preferably in 192.168.0.1
format)?
我如何获得我的 IP 地址(最好是192.168.0.1
格式)?
采纳答案by brm
This example code lists both the interface name (e.g. lo
or eth0
) together with the currently assigned IP address, for all the IPv4 network interfaces that exist on your computer:
此示例代码列出了计算机上存在的所有 IPv4 网络接口的接口名称(例如lo
或eth0
)以及当前分配的 IP 地址:
getifaddrs(&addrs);
tmp = addrs;
while (tmp)
{
if (tmp->ifa_addr && tmp->ifa_addr->sa_family == AF_INET)
{
struct sockaddr_in *pAddr = (struct sockaddr_in *)tmp->ifa_addr;
printf("%s: %s\n", tmp->ifa_name, inet_ntoa(pAddr->sin_addr));
}
tmp = tmp->ifa_next;
}
freeifaddrs(addrs);
回答by alk
For Linux:
对于 Linux:
To get all interfaces local to the machine use getifaddrs()
.
要获取机器本地的所有接口,请使用getifaddrs()
.
There is an example at the end of the page linked above.
上面链接的页面末尾有一个示例。