zoukankan      html  css  js  c++  java
  • Linux C 获取本机所有网卡的 IP,Mask

    0 运行环境

    • 本机系统:Windows 10

    • 虚拟机软件:Oracle VM VirtualBox 6

    • 虚拟机系统:Ubuntu 18

    1 代码

    #include <sys/ioctl.h>
    #include <net/if.h>
    #include <netinet/in.h>
    #include <arpa/inet.h>
    #include <string.h>
    #include <stdio.h>
    
    int get_localIPAndMask(char *ip,char *mask)
    {
    
            int fd, intrface, retn = 0;
    
            struct ifreq buf[INET_ADDRSTRLEN];
    
            struct ifconf ifc;
    
            if ((fd = socket(AF_INET, SOCK_DGRAM, 0)) >= 0)
    
            {
    
                    ifc.ifc_len = sizeof(buf);
    
                    // caddr_t,Linux内核源码里定义的:typedef void *caddr_t;
    
                    ifc.ifc_buf = (caddr_t)buf;
    
                    if (!ioctl(fd, SIOCGIFCONF, (char *)&ifc))
    
                    {
                            intrface = ifc.ifc_len/sizeof(struct ifreq);
    
                            while (intrface-- > 0)
    
                            {
                                    if (!(ioctl(fd, SIOCGIFADDR, (char *)&buf[intrface])))
                                    {
    
                                            ip = (inet_ntoa(((struct sockaddr_in*)(&buf[intrface].ifr_addr))->sin_addr));
    
                                            printf("IP:%s
    ", ip);
                                    }
    
                                     if (!(ioctl(fd, SIOCGIFNETMASK, (char *)&buf[intrface])))
                                    {
                                            mask = (inet_ntoa(((struct sockaddr_in*)(&buf[intrface].ifr_addr))->sin_addr));
    
                                            printf("mask:%s
    ", mask);
                                    }
    
                            }
    
                    }
    
            close(fd);
    
            return 0;
    
            }
    
    }
    
    int main()
    
    {
            char ip[64];
    
            memset(ip, 0, sizeof(ip));
    
            char mask[64];
    
            memset(mask, 0, sizeof(mask));
    
            get_localIPAndMask(ip,mask);
    
            return 0;
    }
    

    2 运行结果

    与 ifconfig 验证一致,成功:

  • 相关阅读:
    一个很好的菜单源码
    在盗版xp下安装ie7正式版 
    [导入]买新手机了
    [导入]手机解锁全集
    12种找工作方式的成功率
    Kerberos的原理 3
    Kerberos的原理 4
    Kerberos的原理 1
    jQuery 原理的模拟代码 6 代码下载
    Hashtable 中的键值修改问题
  • 原文地址:https://www.cnblogs.com/PikapBai/p/13699162.html
Copyright © 2011-2022 走看看