簡體   English   中英

獲取本地主機名和IP地址的C ++ Windows函數調用

[英]C++ Windows function call that get local hostname and IP address

是否有內置的Windows C ++函數調用,可以獲取主機名和IP地址? 謝謝。

要獲取主機名,您可以使用: gethostname或async方法WSAAsyncGetHostByName

要獲取地址信息,您可以使用: getaddrinfo或unicode版本GetAddrInfoW

您可以使用Win32 API獲取有關計算機名稱(如域)的更多信息: GetComputerNameEx

這是一個多平台解決方案...... Windows,Linux和MacOSX。 您可以獲取IP地址,端口,sockaddr_in,端口。

BOOL GetMyHostName(LPSTR pszBuffer, UINT nLen)
{
    BOOL ret;

    ret = FALSE;

    if (pszBuffer && nLen)
    {
        if ( gethostname(pszBuffer, nLen) == 0 )
            ret = TRUE;
        else
            *pszBuffer = '\0';
    }

    return ret;
}


ULONG GetPeerName(SOCKET _clientSock, LPSTR _pIPStr, UINT _IPMaxLen, int *_pport)
{
    struct sockaddr_in sin;
    unsigned long ipaddr;


    ipaddr = INADDR_NONE;

    if (_pIPStr && _IPMaxLen)
        *_pIPStr = '\0';

    if (_clientSock!=INVALID_SOCKET)
    {
        #if defined(_WIN32)
        int  locallen;
        #else
        UINT locallen;
        #endif

        locallen = sizeof(struct sockaddr_in);

        memset(&sin, '\0', locallen);

        if (getpeername(_clientSock, (struct sockaddr *) &sin, &locallen) == 0)
        {
            ipaddr = GetSinIP(&sin, _pIPStr, _IPMaxLen);

            if (_pport)
                *_pport = GetSinPort(&sin);
        }
    }

    return ipaddr;
}


ULONG GetSinIP(struct sockaddr_in *_psin, LPSTR pIPStr, UINT IPMaxLen)
{
    unsigned long ipaddr;

    ipaddr = INADDR_NONE;

    if (pIPStr && IPMaxLen)
        *pIPStr = '\0';

    if ( _psin )
    {
        #if defined(_WIN32)
        ipaddr = _psin->sin_addr.S_un.S_addr;
        #else
        ipaddr = _psin->sin_addr.s_addr;
        #endif

        if (pIPStr && IPMaxLen)
        {
            char  *pIP;
            struct in_addr in;

            #if defined(_WIN32)
            in.S_un.S_addr = ipaddr;
            #else
            in.s_addr = ipaddr;
            #endif

            pIP = inet_ntoa(in);

            if (pIP && strlen(pIP) < IPMaxLen)
                strcpy(pIPStr, pIP);
        }
    }

    return ipaddr;
}


int GetSinPort(struct sockaddr_in *_psin)
{
    int port;

    port = 0;

    if ( _psin )
        port = _Xntohs(_psin->sin_port);

    return port;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM