CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 5 of 5
  1. #1
    Join Date
    Apr 2002
    Posts
    5

    How to determine IP address ?

    Hello,

    I need to determine the actual IP address of the machine I'm working on. This machine is on dialup and gets IPs assigned dynamically.
    I'm working on Windows OS.

    Any hints on how to do this with C/C++ ?

    Thx

    BPCW
    Last edited by Andreas Masur; May 12th, 2003 at 03:55 PM.

  2. #2
    Join Date
    May 2002
    Location
    Manchester, UK
    Posts
    105
    I once needed to get the name of the local machine. To achieve this I opened a windows socket using WSAStartup(...) and then called gethostname(...). This gets youthe local machine name. I think you should then call gethostbyname(...) specifying the local machine namem this will return struct hostent* which should contain the IP Address. not sure exactly how you decode this struct though.

    Don't forget to call WSACleanUp(...) to free the socket resources when you have finished.

    Hope this points you in the right direction

  3. #3
    Join Date
    Feb 2002
    Posts
    5,757
    Here is one using using Winsock 2.

    -----
    addrinfo hints, *result = NULL;
    memset(&hints, 0, sizeof(hints));
    hints.ai_flags = AI_PASSIVE;
    hints.ai_family = AF_UNSPEC;
    hints.ai_socktype = SOCK_STREAM;
    hints.ai_protocol = IPPROTO_TCP;
    char m_cIP[12];
    std::string m_sHost = "",
    m_sPort = "21";

    if (getaddrinfo(static_cast<LPCTSTR>(m_sHost.c_str()), m_sPort.c_str(), &hints, &result) != 0)
    // error
    return false;

    if (getnameinfo(result->ai_addr, result->ai_addrlen, m_cIP, 256, NULL, 0, NI_NUMERICHOST) != 0)
    // error
    return false;

    freeaddrinfo(result);
    // m_cIP holds your IP
    -----

    Kuphryn

  4. #4
    Join Date
    May 2003
    Posts
    3
    can somebody explain that last bit of code and how to implement it??

  5. #5
    Join Date
    May 2000
    Location
    KY, USA
    Posts
    18,652
    Take a look at this FAQ...

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