static std::string GetHostIpByETHName()

in util.cpp [58:127]


static std::string GetHostIpByETHName()
{
#ifdef _MSC_VER
    DWORD dwSize = 0, dwRetVal = 0;
    PMIB_IPADDRTABLE pIPAddrTable = nullptr;


    GetIpAddrTable(pIPAddrTable, &dwSize, 0);

    pIPAddrTable = (MIB_IPADDRTABLE*)malloc(dwSize);
    if (!pIPAddrTable)
    {
        return "";
    }
    if ((dwRetVal = GetIpAddrTable(pIPAddrTable, &dwSize, 0)) == NO_ERROR)
    {
        for (int i = 0; i < (int)pIPAddrTable->dwNumEntries; ++i)
        {
            if (pIPAddrTable->table[i].wType & (MIB_IPADDR_DELETED | MIB_IPADDR_DISCONNECTED | MIB_IPADDR_TRANSIENT))
            {
                continue;
            }
            struct in_addr addr;
            addr.S_un.S_addr = (u_long)pIPAddrTable->table[i].dwAddr;
            string ip = inet_ntoa(addr);
            if (ip == "127.0.0.1") // rm loopback
            {
                continue;
            }
            free(pIPAddrTable);
            return ip;
        }
    }
    if (pIPAddrTable)
    {
        free(pIPAddrTable);
    }
    return "";
#else
    int sock;
    struct sockaddr_in sin;
    struct ifreq ifr;

    sock = socket(AF_INET, SOCK_DGRAM, 0);
    if (sock == -1)
    {
        return string();
    }

    // use eth0 as the default ETH name
    strncpy(ifr.ifr_name, "eth0", IFNAMSIZ);
    ifr.ifr_name[IFNAMSIZ - 1] = 0;

    if (ioctl(sock, SIOCGIFADDR, &ifr) < 0)
    {
        close(sock); // added by gaolei 13-10-09
        return string();
    }

    memcpy(&sin, &ifr.ifr_addr, sizeof(sin));

    char* ipaddr = inet_ntoa(sin.sin_addr);
    close(sock); // added by gaolei 13-10-09
    if (ipaddr == NULL)
    {
        return string();
    }
    return string(ipaddr);
#endif
}