LinuxSir.cn,穿越时空的Linuxsir!

 找回密码
 注册
搜索
热搜: shell linux mysql
查看: 930|回复: 1

如何查询网卡信息?

[复制链接]
发表于 2006-4-19 16:01:18 | 显示全部楼层 |阅读模式
请问如何在程序中查询系统安装了几块网卡以及每块网卡的IP?最好不要是读配置文件那种实现方法.
发表于 2006-4-20 15:16:02 | 显示全部楼层
抄的:


#include <stdio.h>
#include <sys/ioctl.h>
#include <sys/socket.h>
#include <net/if.h>
#include <arpa/inet.h>

/* maximum NICs, change this as neccessary */
#define MAXINTERFACES   16

int main (int argc, char *argv[])
{
    int fd, n, r = 0;
    struct ifreq buf[MAXINTERFACES];
    struct ifconf ifc;

    /* try to open a AF_INET socket */
    if ((fd = socket (AF_INET, SOCK_DGRAM, 0)) < 0)
        exit(1);

    ifc.ifc_len = sizeof(buf);
    ifc.ifc_buf = (caddr_t) buf;

    /* try to get all interface configuration information */
    if (ioctl (fd, SIOCGIFCONF, (char *) &ifc)!=0)
        exit(2);

    /* the number of NIC cards */
    n = ifc.ifc_len / sizeof (struct ifreq);

    while (n-- > 0)
    {
        /* printf ("net device %s\n", buf[n].ifr_name); */

        /* get the IP address of this NIC card */
        if (!(ioctl (fd, SIOCGIFADDR, (char *) &buf[n])))
            puts(inet_ntoa(((struct sockaddr_in*)(&buf[n].ifr_addr))->sin_addr));

        else ++r;
    }
    close (fd);
    return r;
}
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 注册

本版积分规则

快速回复 返回顶部 返回列表