linux c++ 获取所有网卡IP地址源码

动态 未结 0 82
小小草
小小草 LV1 2023年9月23日 23:40 发表
可以使用Linux系统提供的socket API来获取所有网络接口信息,然后从中获取每个网卡的IP地址。下面是一个示例代码: ```c++ #include #include #include #include #include #include #include int main() { int sock = socket(AF_INET, SOCK_DGRAM, 0); if (sock < 0) { perror("socket"); exit(1); } struct ifreq ifr; struct ifconf ifc; char buf[1024]; ifc.ifc_len = sizeof(buf); ifc.ifc_buf = buf; if (ioctl(sock, SIOCGIFCONF, &ifc) < 0) { perror("ioctl"); close(sock); exit(1); } struct ifreq *ifr_array = (struct ifreq *)buf; int num_interfaces = ifc.ifc_len / sizeof(struct ifreq); for (int i = 0; i < num_interfaces; i++) { strncpy(ifr.ifr_name, ifr_array[i].ifr_name, IFNAMSIZ - 1); if (ioctl(sock, SIOCGIFFLAGS, &ifr) < 0) { perror("ioctl"); continue; } if (!(ifr.ifr_flags & IFF_UP)) { continue; } if (ioctl(sock, SIOCGIFADDR, &ifr) < 0) { perror("ioctl"); continue; } struct sockaddr_in *addr = (struct sockaddr_in *)&ifr.ifr_addr; printf("IP address of %s: %s\n", ifr.ifr_name, inet_ntoa(addr->sin_addr)); } close(sock); return 0; } ``` 该程序创建了一个socket,并通过ioctl函数获取了所有网络接口信息。然后遍历每个接口,判断是否为启用状态(即标志位中是否包含IFF_UP),如果是则获取其IP地址信息。最后将IP地址以字符串形式输出。
收藏(0)  分享
相关标签: 智能问答
问题没解决?让AI助手帮你作答 AI助手
0个回复
  • 消灭零回复