Windows c++获取本地ip

int GetLocalIp(vector &vIp)
{
    WSADATA wsaData;
    int iRet = WSAStartup(((2 << 8) & 0xffff) | (2 & 0xff), &wsaData);
    if (iRet != 0) {
        std::cerr << "WSAStartup failed: " << iRet << std::endl;
        return 1;
    }

    // 获取本机名
    char hostname[256];
    int result = gethostname(hostname, sizeof(hostname));
    if (result != 0) {
        std::cerr << "gethostname failed: " << WSAGetLastError() << std::endl;
        WSACleanup();
        return 1;
    }

    // 获取主机信息
    struct hostent* phe = gethostbyname(hostname);
    if (phe == nullptr) {
        std::cerr << "gethostbyname failed: " << WSAGetLastError() << std::endl;
        WSACleanup();
        return 1;
    }

    // 遍历所有的IP地址
    for (int i = 0; phe->h_addr_list[i] != 0; ++i) {
        struct in_addr addr;
        memcpy(&addr, phe->h_addr_list[i], sizeof(struct in_addr));
        vIp.push_back(inet_ntoa(addr));
        std::cout << "Local IP " << i + 1 << ": " << inet_ntoa(addr) << std::endl;
    }

    WSACleanup();
}

你可能感兴趣的:(windows,tcp/ip,网络协议)