从接口名称中查找 IP 地址 [英] Finding an IP address from an interface name

查看:16
本文介绍了从接口名称中查找 IP 地址的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

On a Linux box, the common interface names look like eth0, eth1, etc. I know how to find at least one IP address using gethostbyname or similar functions, but I don't know any way to specify which named interface I want the IP address of. I could use ifconfig and parse the output, but shelling out for this information seems... inelegant.

有没有办法将所有接口及其 IP 地址(可能还有 MAC 地址)枚举到一个集合中?或者至少类似于 gethostbyinterface("eth0")?

Is there a way to, say, enumerate all the interfaces and their IP addresses (and maybe MAC addresses) into a collection? Or at least something along the lines of 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
", ip);
    else
        printf("No IP
");
    return 0;
 }

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

Update: Moved dead link to a comment (for posterity) (thanks @obayhan), and added syntax highlighting.

这篇关于从接口名称中查找 IP 地址的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆