[英]Finding an IP address from an interface name
在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 <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 <jaco@kroon.co.za>
*/
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),並添加語法突出顯示。
編輯:我看到你不喜歡炮擊。 然后你可以看看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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.