gpt4 book ai didi

linux - 从接口(interface)名称查找 IP 地址

转载 作者:IT王子 更新时间:2023-10-29 00:51:42 28 4
gpt4 key购买 nike

在 Linux 机器上,常见的接口(interface)名称看起来像 eth0、eth1 等。我知道如何使用 gethostbyname 或类似函数找到至少一个 IP 地址,但我不知道指定我想要哪个命名接口(interface)的 IP 地址的方法。我可以使用 ifconfig 并解析输出,但是为了这些信息而掏空似乎……不够优雅。

有没有办法将所有接口(interface)及其 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),并添加了语法高亮显示。

关于linux - 从接口(interface)名称查找 IP 地址,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/259389/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com