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

查看:109
本文介绍了从接口名称查找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\n", ip);
    else
        printf("No IP\n");
    return 0;
 }

更新:将无效链接移至注释(供后代使用)(感谢@obayhan),并添加了语法高亮显示.

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

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

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