[英]detecting connected interface using c++ in linux
I want to detect which interface is now connected; 我想检测现在连接的接口; and I have three 3g-modem connections and two lan connections to the server(my device didn't support wlan). 我有三个3g-modem连接和两个lan连接到服务器(我的设备不支持wlan)。 I mean the type of connection is not important but the interface name and specifics is what important for me. 我的意思是连接类型并不重要,但接口名称和细节对我来说非常重要。 I want to detect connected interface in my program that I wrote in c++. 我想检测我用c ++编写的程序中的连接接口。 please tell me how to detect connected interface in c++?(root permission is not a problem.) 请告诉我如何在c ++中检测连接的接口?(root权限不是问题。)
Use ioctl
SIOCGIFFLAGS
to check is the interface UP and RUNNING: 使用ioctl
SIOCGIFFLAGS
检查接口UP和RUNNING:
struct ifreq ifr;
memset( &ifr, 0, sizeof(ifr) );
strcpy( ifr.ifr_name, ifrname );
if( ioctl( dummy_fd, SIOCGIFFLAGS, &ifr ) != -1 )
{
up_and_running = (ifr.ifr_flags & ( IFF_UP | IFF_RUNNING )) == ( IFF_UP | IFF_RUNNING );
}
else
{
// error
}
Input variable is ifrname
. 输入变量是ifrname
。 It should be the interface name "eth0", eth1", "ppp0" .... 它应该是接口名称“eth0”,eth1“,”ppp0“....
Because ioctl()
needs a file descriptor as parameter, you can use for example some temporary UDP socket for that: 因为ioctl()
需要一个文件描述符作为参数,你可以使用例如一些临时UDP套接字:
dummy_fd = socket( AF_INET, SOCK_DGRAM, 0 );
Remember to close the socket, when not used anymore. 记得关闭插座,不再使用时。
If you are using NetworkManager, you can use it's API . 如果您使用的是NetworkManager,则可以使用它的API 。 You can either use the D-Bus API, the GLib wrapping, C++ Bindings for D-Bus . 您可以使用D-Bus API,GLib包装, D-Bus的C ++绑定 。
If you are using Qt, you can directly use QtNetwork . 如果您使用的是Qt,则可以直接使用QtNetwork 。
Of course, you can also go very low-level and use ioctl(7)
. 当然,你也可以使用ioctl(7)
。 See lsif by Adam Risi for an example. 请参阅Adam Risi的 lsif作为示例。
You can also use netlink route sockets. 您还可以使用netlink路由套接字。 See libnetlink library, or man 7 netlink and man 7 rtnetlink. 请参阅libnetlink库,或man 7 netlink和man 7 rtnetlink。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.