Linux 下获取本机所有网卡 以及 网卡对应ip 列表
生活随笔
收集整理的這篇文章主要介紹了
Linux 下获取本机所有网卡 以及 网卡对应ip 列表
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
簡單record 一下
#include <arpa/inet.h> // 'struct sockaddr_in'
#include <errno.h>
#include <net/if.h> // 'struct ifreq' and 'struct if_nameindex'
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/ioctl.h> // ioctl
#include <unistd.h>int GetInterfaceIp(const char *eth_inf, char *ip) {int sd;struct sockaddr_in sin;struct ifreq ifr;sd = socket(AF_INET, SOCK_DGRAM, 0);if (-1 == sd) {printf("socket error: %s\n", strerror(errno));return -1;}strncpy(ifr.ifr_name, eth_inf, IFNAMSIZ);ifr.ifr_name[IFNAMSIZ - 1] = 0;// if error: No such deviceif (ioctl(sd, SIOCGIFADDR, &ifr) < 0) {printf("iterfac %s ioctl error: %s\n", eth_inf, strerror(errno));close(sd);return -1;}printf("interfac: %s, ip: %s\n", eth_inf,inet_ntoa(((struct sockaddr_in *)&ifr.ifr_addr)->sin_addr));close(sd);return 0;
}void GetAllInterfaceNames() {struct if_nameindex *if_nidxs, *intf;// the begin of if_name index.if_nidxs = if_nameindex();if (if_nidxs != NULL) {for (intf = if_nidxs; intf->if_index != 0 || intf->if_name != NULL;intf++) {char ip[1024];GetInterfaceIp(intf->if_name, ip);}if_freenameindex(if_nidxs);}
}int main() {GetAllInterfaceNames();return 0;
}
編譯及運行:
$ g++ -O0 -g get_ip.c -o get_ip
$ ./get_ip
interfac: lo, ip: 127.0.0.1
iterfac eth01 ioctl error: Cannot assign requested address
iterfac eth02 ioctl error: Cannot assign requested address
interfac: bond0, ip: 10.192.25.173
總結
以上是生活随笔為你收集整理的Linux 下获取本机所有网卡 以及 网卡对应ip 列表的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 关于 fallocate 文件系统预分配
- 下一篇: “绿冻杨枝折”上一句是什么