Click to See Complete Forum and Search --> : How to determine IP address ?


BPCW
July 25th, 2002, 05:14 AM
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

Simon Wilkins
July 25th, 2002, 05:28 AM
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

kuphryn
July 29th, 2002, 12:37 PM
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

marvinklein
May 12th, 2003, 03:04 PM
can somebody explain that last bit of code and how to implement it??

Andreas Masur
May 12th, 2003, 04:00 PM
Take a look at this FAQ (http://www.codeguru.com/forum/showthread.php?s=&threadid=233261)...