Home  >  Q&A  >  body text

linux 下获取本机地址和掩码

PHP中文网PHP中文网2714 days ago340

reply all(2)I'll reply

  • 巴扎黑

    巴扎黑2017-04-17 13:15:14

    I feel that there is a problem with inet_ntoa printing subnet mask under Linux. This program can output correctly on Mac system.
    I wrote a function myself that can output the correct result.

    #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;
    }
    
    

    reply
    0
  • PHP中文网

    PHP中文网2017-04-17 13:15:14

    Use the inet_ntop function to get the correct result

    reply
    0
  • Cancelreply