• C语言通过枚举网卡,API接口可查看man 7 netdevice--获取接口IP地址


    /*代码来自StackOverflow: http://stackoverflow.com/questions/212528/linux-c-get-the-ip-address-of-local-computer */
    #include <stdio.h>      
    #include <sys/types.h>
    #include <ifaddrs.h>
    #include <netinet/in.h> 
    #include <string.h> 
    #include <arpa/inet.h>
    
    int main (int argc, const char * argv[]) {
        struct ifaddrs * ifAddrStruct=NULL;
        void * tmpAddrPtr=NULL;
    
        getifaddrs(&ifAddrStruct);
    
        while (ifAddrStruct!=NULL) {
            if (ifAddrStruct->ifa_addr->sa_family==AF_INET) { // check it is IP4
                // is a valid IP4 Address
                tmpAddrPtr=&((struct sockaddr_in *)ifAddrStruct->ifa_addr)->sin_addr;
                char addressBuffer[INET_ADDRSTRLEN];
                inet_ntop(AF_INET, tmpAddrPtr, addressBuffer, INET_ADDRSTRLEN);
                printf("%s IP Address %s
    ", ifAddrStruct->ifa_name, addressBuffer); 
            } else if (ifAddrStruct->ifa_addr->sa_family==AF_INET6) { // check it is IP6
                // is a valid IP6 Address
                tmpAddrPtr=&((struct sockaddr_in *)ifAddrStruct->ifa_addr)->sin_addr;
                char addressBuffer[INET6_ADDRSTRLEN];
                inet_ntop(AF_INET6, tmpAddrPtr, addressBuffer, INET6_ADDRSTRLEN);
                printf("%s IP Address %s
    ", ifAddrStruct->ifa_name, addressBuffer); 
            } 
            ifAddrStruct=ifAddrStruct->ifa_next;
        }
        return 0;
    }
  • 相关阅读:
    程序员常去的14个顶级开发社区
    为何技术领域中女程序员较少?
    为何技术领域中女程序员较少?
    为何技术领域中女程序员较少?
    关于HTTP和HTTPS的区别
    关于HTTP和HTTPS的区别
    关于HTTP和HTTPS的区别
    Coupled model
    java和javascript日期详解
    Java 线程总结(十四)
  • 原文地址:https://www.cnblogs.com/yaox/p/6604522.html
Copyright © 2020-2023  润新知