获取当前机器 IP

std::string GetLocalIP()         
{        
    struct ifreq req; 
    int sock_fd; 
    char szLocalIP[16]= {0};
    string strLocalIP="";

    sock_fd = socket(AF_INET,SOCK_STREAM,0);
    if(sock_fd < 0)
        return strLocalIP; 
                         
    snprintf(req.ifr_name,IFNAMSIZ,"eth1");
    if(ioctl(sock_fd,SIOCGIFADDR,(char*)&req) < 0)
    {
        close(sock_fd);
        return strLocalIP;
    }
     
    snprintf(szLocalIP,sizeof(szLocalIP)-1,inet_ntoa(((struct sockaddr_in*)(&req.ifr_addr))->sin_addr));
    close(sock_fd);
    strLocalIP=szLocalIP;
    return strLocalIP; 
}
std::string getCurrentIP() {
    const char* pSzIpAddr = "0.0.0.0";
    char szIpAddrBuffer[32] = {0};
    struct ifaddrs* pIfAddrs;
    if (getifaddrs(&pIfAddrs) == 0)
    {
        for (struct ifaddrs* pIfAddr = pIfAddrs; pIfAddr; pIfAddr = pIfAddr->ifa_next)
        {
            if (pIfAddr->ifa_addr == NULL || !(pIfAddr->ifa_flags & IFF_UP) || strncmp(pIfAddr->ifa_name, "eth1", strlen("eth1")) != 0)
            {
                continue;
            }
            if (inet_ntop(pIfAddr->ifa_addr->sa_family, &((struct sockaddr_in *)pIfAddr->ifa_addr)->sin_addr, szIpAddrBuffer, sizeof(szIpAddrBuffer)))
            {   
                pSzIpAddr = szIpAddrBuffer;
                break;                
            }
        }
        freeifaddrs(pIfAddrs);
    }
    return std::string(pSzIpAddr);
}

Leave a Reply

Your email address will not be published. Required fields are marked *