linux 下获取本机地址和掩码-问答-阿里云开发者社区-阿里云

开发者社区> 问答> 正文

linux 下获取本机地址和掩码

a123456678 2016-06-21 14:59:53 1075

screenshot

#include <iostream>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <ifaddrs.h>

using namespace std;

int main(void) {
    struct ifaddrs* myaddrs;
    struct sockaddr_in *ss, *kk;
    if (getifaddrs(&myaddrs) == 0) {
        for (struct ifaddrs* ifa = myaddrs; ifa != NULL; ifa = ifa->ifa_next) {
        ss = (struct sockaddr_in*) ifa->ifa_addr;
        kk = (struct sockaddr_in*) ifa->ifa_netmask;
        if (ss->sin_family == AF_INET)
            cout << "sa_family:" << ss->sin_family << " " << ifa->ifa_name << ":" << inet_ntoa(ss->sin_addr) << " netmask:" << inet_ntoa(kk->sin_addr) << endl;
        }
    }
    return 0;
}
Linux
分享到
取消 提交回答
全部回答(1)
  • a123456678
    2019-07-17 19:44:58
    #include <iostream>
    #include <sys/socket.h>
    #include <arpa/inet.h>
    #include <ifaddrs.h>
    #include <sstream>
    
    using namespace std;
    
    string getip(const sockaddr_in* addr)
    {
        ostringstream s;
        int a = ntohl(addr->sin_addr.s_addr);
        s << ((a >> 24) & 0xFF) << '.' << ((a >> 16) & 0xFF) << '.'
          << ((a >> 8) & 0xFF) << '.' << (a & 0xFF);
        return s.str();
    }
    
    
    int main(void) 
    {
        struct ifaddrs* myaddrs;
        struct sockaddr_in *ss, *kk;
        char buf[100];
        if (getifaddrs(&myaddrs) == 0) {
            for (struct ifaddrs* ifa = myaddrs; ifa != NULL; ifa = ifa->ifa_next) {
                ss = (struct sockaddr_in*) ifa->ifa_addr;
                kk = (struct sockaddr_in*) ifa->ifa_netmask;
                if (ss->sin_family == AF_INET)
                    cout << ifa->ifa_name << ":" << getip(ss) << " netmask:" << getip(kk) << endl;
            }
        }
        return 0;
    }
    
    0 0
开发与运维
使用钉钉扫一扫加入圈子
+ 订阅

集结各类场景实战经验,助你开发运维畅行无忧

推荐文章
相似问题