从接口名称查找IP地址
问题描述:
在Linux机器上,通用接口名称看起来像eth0,eth1等。我知道如何使用gethostbyname
或类似函数找到至少一个IP地址,但我不知道任何方式来指定我想要哪个指定接口的IP地址。我可以使用ifconfig并解析输出,但是对于这些信息而言,似乎......不够优雅。从接口名称查找IP地址
有没有一种办法,也就是说,枚举所有的接口和它们的IP地址(也许MAC地址)到一个集合?或者至少沿着gethostbyinterface("eth0")
的方向行事?
答
从TLUG:
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/ioctl.h>
#include <net/if.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <string.h>
#include <stdio.h>
#include <unistd.h>
/**
* 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 <[email protected]>
*/
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;
}
+0
当然有一个缺点:打开虚拟套接字。无论如何,工作很好。 – 2008-11-03 18:43:32
答
编辑:我看到你不喜欢炮击。然后你可以看看ifconfig如何完成它的工作(它至少从/ proc中提取了一些信息)。
当你有接口的名称,你可以这样做(在你的shell):
ifconfig eth0 | grep 'inet addr' | sed -e 's/:/ /' | awk '{print $3}'
枚举接口,你可以使用这个:
ifconfig | egrep '^[^ ]' | awk '{print $1}'
组合:
for x in `ifconfig | egrep '^[^ ]' | awk '{print $1}'`; do
echo -n "${x}"
echo -n " "
ifconfig "${x}" | grep 'inet addr' | sed -e 's/:/ /' | awk '{print $3}'
done
请参阅此问题:获取本地计算机的IP地址(http://*.com/questions/212528) – camh 2008-11-04 03:15:10