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

前端 未结 2 1868
悲哀的现实
悲哀的现实 2020-12-16 03:01

Is there built-in windows C++ function call that can get hostname and IP address? Thanks.

相关标签:
2条回答
  • 2020-12-16 03:40

    Here is a multiplatform solution... Windows, Linux and MacOSX. You can obtain ip address, port, sockaddr_in, port.

    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;
    }
    
    0 讨论(0)
  • 2020-12-16 04:07

    To get the hostname you can use: gethostname or the async method WSAAsyncGetHostByName

    To get the address info, you can use: getaddrinfo or the unicode version GetAddrInfoW

    You can get more information about the computer name like the domain by using the Win32 API: GetComputerNameEx.

    0 讨论(0)
提交回复
热议问题