如何在Linux上以C语言获取我的IP地址? [重复]

时间:2022-07-18 07:09:26

This question already has an answer here:

这个问题在这里已有答案:

How could I get my IP address (preferably in 192.168.0.1 format)?

我怎样才能获得我的IP地址(最好是192.168.0.1格式)?

2 个解决方案

#1


9  

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);

#2


7  

For Linux:

To get all interfaces local to the machine use getifaddrs().

要获取机器本地的所有接口,请使用getifaddrs()。

There is an example at the end of the page linked above.

上面链接的页面末尾有一个例子。

#1


9  

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);

#2


7  

For Linux:

To get all interfaces local to the machine use getifaddrs().

要获取机器本地的所有接口,请使用getifaddrs()。

There is an example at the end of the page linked above.

上面链接的页面末尾有一个例子。