linux cc++查看eth0网口是否存在存在是否启动给出实现代码
以下是一个用C/C++编写的示例代码,来查看eth0网口是否存在并判断是否启动:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/socket.h>
#include <sys/ioctl.h>
#include <netinet/in.h>
#include <net/if.h>
int main() {
int sock;
struct ifreq ifr;
// 创建一个socket
sock = socket(AF_INET, SOCK_DGRAM, 0);
if (sock < 0) {
perror("socket");
exit(1);
}
// 设置要查询的网口名称
strncpy(ifr.ifr_name, "eth0", IFNAMSIZ - 1);
// 获取网口标志位
if (ioctl(sock, SIOCGIFFLAGS, &ifr) < 0) {
perror("ioctl");
close(sock);
exit(1);
}
// 判断网口是否存在
if (ifr.ifr_flags & IFF_UP) {
printf("eth0网口存在并已启动\n");
} else {
printf("eth0网口不存在或未启动\n");
}
close(sock);
return 0;
}
该代码使用了socket函数创建一个socket,使用ioctl函数通过SIOCGIFFLAGS标志来获取网口的标志位,然后判断网口是否存在并启动
原文地址: https://www.cveoy.top/t/topic/hY05 著作权归作者所有。请勿转载和采集!