2

如何从 Linux 中的 C 程序获取网络接口的类型名称?

我尝试使用getifaddr来访问网络接口,并且得到了我需要的一切,除了它的类型名称。有什么想法可以做到吗?

我还是 Linux 的新手,因此对任何变通方法或示例代码的任何评论都将不胜感激。

编辑

详细说明问题。基本上,在做的时候ifconfig我可以得到这样的东西:

eth0 链路封装:以太网 HWaddr 00:0C:29:40:93:9C
inet 地址:192.168.154.102 广播:192.168.154.255 掩码:255.255.255.0
inet6 地址:fe80::20c:29ff:fe40:939c/64 范围:链接
UP BROADCAST RUNNING MULTICAST MTU:1500 Metric:1
RX 数据包:14785 错误:0 丢弃:0 超限:0 帧:0
TX 数据包:429 错误:0 丢弃:0 超限:0 运营商:0
碰撞:0 txqueuelen:1000
RX 字节:961439 (938.9 KiB) TX 字节:71866 (70.1 KiB)
中断:67 基地址:0x2000

这是我理解的 eth0 是接口名称。虽然可以有多个网络接口(eth0、eth1、eth2)和多个虚拟接口(tap0、tap1 等)和无线接口,但它们都是以太网接口。

loopbacks 也一样,lo 作为接口名,它的接口是Local Loopback。

所以问题是,当我事先不知道使用了哪些接口以及有多少他们在机器里。

希望我能正确解释这一点。

4

5 回答 5

3

You might try to use RTNETLINK from Netlink(1,2). See Manipulating the Networking Environment Using RTNETLINK for an exemple.

于 2012-12-27T10:10:19.687 回答
1

There's no ioctl that returns the link encapsulation, if you strace ifconfig or have a look at its source code you will see that it uses a table look-up to find the name of the link encapsulation. This is from net-tools source code, as you can see the names are statically initialized:

//lib/hw.c
void hwinit()
{
    loop_hwtype.title = _("Local Loopback");
    unspec_hwtype.title = _("UNSPEC");
#if HAVE_HWSLIP
    slip_hwtype.title = _("Serial Line IP");
    cslip_hwtype.title = _("VJ Serial Line IP");
    slip6_hwtype.title = _("6-bit Serial Line IP");
    cslip6_hwtype.title = _("VJ 6-bit Serial Line IP");
    adaptive_hwtype.title = _("Adaptive Serial Line IP");
#endif
#if HAVE_HWETHER
    ether_hwtype.title = _("Ethernet");
#endif
....
于 2012-12-27T10:31:28.397 回答
1

A simple way would be:

cat /sys/class/net/X/type

(where X is your netdev name, e.g. eth0)

Then compare the number to: http://lxr.linux.no/linux+v3.0/include/linux/if_arp.h#L30

for example:

cat /sys/class/net/eth0/type

output:

1

=> where 1=ARPHRD_ETHER accoridng to if_arp.h header file.

于 2012-12-28T02:35:02.910 回答
0

真正广泛的问题。

Under linux the OS itself can be considered a network interface, the so called "loopback interfaces" admit this kind of options and they are "network interfaces" even if they are virtual and not a real piece of hardware they look the same as your PCI network card or your USB dongle. if you are looking for the networking hardware is suggest to take a look at lshw or to spend time studying how the kernel interfaces itself with the networking resources.

于 2012-12-27T09:31:17.457 回答
0

Unrelated to the question but, in case someone wants to find it on the shell here one way to find the wifi interfaces:

for iface in ` ifconfig | cut -f 1 -d ' ' | sort | grep -v '^$'`
do
if [ -d /sys/class/net/$iface/wireless ];then echo $iface ; fi
done
于 2016-02-06T05:10:39.927 回答