2010-05-29 8 views

Odpowiedz

12

Aby uzyskać nazwę hosta można użyć: gethostname lub metody asynchronicznej WSAAsyncGetHostByName

Aby uzyskać informacje adresowe, można użyć: getaddrinfo lub wersja Unicode GetAddrInfoW

można uzyskać więcej informacji na temat komputera nazwa taka jak domena przy użyciu interfejsu Win32 API: .

4

Oto wieloplatformowe rozwiązanie ... Windows, Linux i MacOSX. Możesz uzyskać adres IP, 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) 
       adjust_str(pIP, pIPStr, IPMaxLen); 
     } 
    } 

    return ipaddr; 
} 


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

    port = 0; 

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

    return port; 
} 
+1

To jest niesamowite, wielkie dzięki! – Stan

+0

jak przetestować swoją funkcję GetSinIP? –

+0

Należy pamiętać, że nazwa hosta zwrócona przez 'gethostname()' to ** nie ** koniecznie nazwa zwrócona przez rozpoznawanie nazw domen dla dowolnego interfejsu hosta! Jednak ** może ** mieć tę samą nazwę, jeśli jest skonfigurowany w ten sposób. – alk

Powiązane problemy