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 验证一致,成功:

  • 相关阅读:
    毕业设计(五)
    毕业设计:周计划任务(四)
    毕业设计:周计划任务(三)
    毕业设计:周计划任务(二)
    毕业设计:周计划任务(一)
    运行jar包
    常见算法
    mybatis入门
    策略模式
    java面2
  • 原文地址:https://www.cnblogs.com/PikapBai/p/13699162.html
Copyright © 2011-2022 走看看