这是在此处的答案中建议的,Get the IP address of the machine , 可以使用 getifaddrs()
获取运行程序的机器的 IP 地址,效果很好 :D:D
但是,在两个不同的系统上运行同一个程序,一个显示
SERVER_ADDRESS lo 127.0.0.1
SERVER_ADDRESS eth0 129.xxx.xxx.xxx
SERVER_ADDRESS virbr0 192.zzz.zzz.1
而另一个显示
SERVER_ADDRESS lo0 127.0.0.1
SERVER_ADDRESS en0 192.yyy.yyy.yyy
我打算使用 strcmp
来区分以太网,但现在我意识到它不能跨系统工作,因为可能会打印出不同的字符串。
是否有函数(或更好的方法)来检查 ifa_name
是否是以太网?
最佳答案
(再次)明确说明:127.0.0.0/255.0.0.0
网络(范围)的所有地址,因为存在从 127.0.0.0
到127.255.255.255
,被定义为本地环回地址。发送给此类的数据不会离开本地机器。
无论如何,因为您已经在使用 getifaddrs()
,所以 live 很容易.. - 只需测试结构的成员 ifa_flags
struct ifaddrs
为 IFF_LOOPBACK
返回,如下所示:
#include <sys/types.h>
#include <ifaddrs.h>
#include <net/if.h> /* for IFF_LOOPBACK */
...
struct ifaddrs * pIfAddrs = NULL;
if (!getifaddrs(&pIfAddrs)) {
/* Test if the first interface is looping back to the local host. */
int iIsLoopBack = (0 != (pIfAddrs->ifa_flags & IFF_LOOPBACK));
...
}
...
/* clean up */
if (pIfAddrs) {
freeifaddrs(pIfAddrs);
pIfAddrs = NULL;
}
...
关于c - 如何区分以太网和其他以太网?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8101934/