加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > Linux > 正文

linux – 从接口名称中查找IP地址

发布时间:2020-12-14 01:28:56 所属栏目:Linux 来源:网络整理
导读:在 Linux机器上,通用接口名称看起来像eth0,eth1等.我知道如何使用gethostbyname或类似功能找到至少一个IP地址,但我不知道如何指定哪个命名接口我想要IP的地址.我可以使用ifconfig并解析输出,但是为这些信息进行炮轰似乎……不优雅. 有没有办法将所有接口及其
在 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: %sn",ip);
    else
        printf("No IPn");
    return 0;
 }

更新:将死链接移至评论(后代)(感谢@obayhan),并添加语法突出显示.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读