我如何得到我的IP地址在C对Linux呢? [英] How do I get my IP address in C on Linux?
本文介绍了我如何得到我的IP地址在C对Linux呢?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我怎么能得到我的IP地址(preferably在 192.168.0.1
格式)?
How could I get my IP address (preferably in 192.168.0.1
format)?
推荐答案
这个例子code列出了两个接口的名称(如罗
或为eth0
)与当前分配的IP地址,所有计算机上存在的IPv4网络接口在一起:
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:
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);
这篇关于我如何得到我的IP地址在C对Linux呢?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文