在Linux机器上,通用接口名称看起来像eth0,eth1等.我知道如何使用gethostbyname
或类似功能找到至少一个IP地址,但我不知道如何指定哪个命名接口我想要IP地址的.我可以使用ifconfig并解析输出,但是为这些信息进行炮轰似乎......不优雅.
有没有办法将所有接口及其IP地址(以及可能的MAC地址)枚举到集合中?或者至少是某些东西gethostbyinterface("eth0")
?
// Originally from http://www.tlug.org.za/wiki/index.php/Obtaining_your_own_IP_address
#include
#include
#include
#include
#include
#include
#include
#include
#include
/**
* getIPv4()
*
* This function takes a network identifier such as "eth0" or "eth0:0" and
* a pointer to a buffer of at least 16 bytes and then stores the IP of that
* device gets stored in that buffer.
*
* it return 0 on success or -1 on failure.
*
* Author: Jaco Kroon
*/
int getIPv4(const char * dev, char * ipv4) {
struct ifreq ifc;
int res;
int sockfd = socket(AF_INET, SOCK_DGRAM, 0);
if(sockfd < 0)
return -1;
strcpy(ifc.ifr_name, dev);
res = ioctl(sockfd, SIOCGIFADDR, &ifc);
close(sockfd);
if(res < 0)
return -1;
strcpy(ipv4, inet_ntoa(((struct sockaddr_in*)&ifc.ifr_addr)->sin_addr));
return 0;
}
int main() {
char ip[16];
if(getIPv4("eth0", ip) == 0)
printf("IPv4: %s\n", ip);
else
printf("No IP\n");
return 0;
}
更新:将死链接移至评论(后代)(感谢@obayhan),并添加语法突出显示.