CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 1 of 1

Threaded View

  1. #1
    Join Date
    May 2000
    Location
    KY, USA
    Posts
    18,652

    Visual C++ Network: How to get the local IP address(es)?

    Q: How to get the local IP address(es)?

    A: The following example will get up to ten assigned IP addresses...

    Code:
    #include <winsock2.h>
    
    // Add 'ws2_32.lib' to your linker options
    
    WSADATA WSAData;
    
    // Initialize winsock dll
    if(::WSAStartup(MAKEWORD(1, 0), &WSAData))
    {
      // Error handling
    }
    
    // Get local host name
    char szHostName[128] = "";
    
    if(::gethostname(szHostName, sizeof(szHostName)))
    {
      // Error handling -> call 'WSAGetLastError()'
    }
    
    // Get local IP addresses
    struct sockaddr_in SocketAddress;
    struct hostent     *pHost        = 0;
    
    pHost = ::gethostbyname(szHostName);
    if(!pHost)
    {
      // Error handling -> call 'WSAGetLastError()'
    }
    
    char aszIPAddresses[10][16]; // maximum of ten IP addresses
    
    for(int iCnt = 0; ((pHost->h_addr_list[iCnt]) && (iCnt < 10)); ++iCnt)
    {
      memcpy(&SocketAddress.sin_addr, pHost->h_addr_list[iCnt], pHost->h_length);
      strcpy(aszIPAddresses[iCnt], inet_ntoa(SocketAddress.sin_addr));
    }
    
    // Cleanup
    WSACleanup();
    As with everything, there exists of course other ways and other information which can be retrieved...some examples can be found in the following knowledge base article.


    Last edited by Andreas Masur; January 21st, 2008 at 09:29 PM.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured