【问题标题】:Finding an IP address from an interface name从接口名称中查找 IP 地址
【发布时间】:2010-09-20 12:54:52
【问题描述】:

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

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

【问题讨论】:

标签: linux network-programming


【解决方案1】:
// 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),并添加语法高亮显示。

【讨论】:

  • 当然有一个缺点:你打开了一个虚拟套接字。无论如何,干得好。
【解决方案2】:

编辑:我看到你不喜欢炮击。然后你可以看看 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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-08-02
    • 2019-08-19
    • 1970-01-01
    • 2021-02-12
    • 2016-06-09
    • 1970-01-01
    • 2017-01-25
    相关资源
    最近更新 更多