linux 下获取本机地址和掩码
PHP中文网
PHP中文网 2017-04-17 13:13:14
0
2
369
PHP中文网
PHP中文网

认证高级PHP讲师

reply all(2)
巴扎黑

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

洪涛

Use the inet_ntop function to get the correct result

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!