Reputation: 11935
What is the best way to get your IP address and then convert it into bytes using C++? I need something cross-platform. I found a lot but I do not know what is the best technique.
Upvotes: 0
Views: 919
Reputation: 9573
As Ben stated, you could use a non-standard library that has implementations for many OSs. By no means is boost the silver bullet, but the boost asio library is a really useful, well-designed, portable networking library with implementations for many operating systems. Specifically asio provides the ip::host_name method.
Upvotes: 1
Reputation: 562
Two methods you can use to convert an IP to a string are inet_ntoa (IPv4 only) or getnameinfo with the flag NI_NUMERICHOST (IPv4 and IPv6).
Upvotes: 0
Reputation: 7296
You can use gethostname followed by gethostbyname to get your local interface internal IP.
You can try this code:
struct IPv4
{
unsigned char b1, b2, b3, b4;
};
bool getMyIP(IPv4 & myIP)
{
char szBuffer[1024];
#ifdef WIN32
WSADATA wsaData;
WORD wVersionRequested = MAKEWORD(2, 0);
if(::WSAStartup(wVersionRequested, &wsaData) != 0)
return false;
#endif
if(gethostname(szBuffer, sizeof(szBuffer)) == SOCKET_ERROR)
{
#ifdef WIN32
WSACleanup();
#endif
return false;
}
struct hostent *host = gethostbyname(szBuffer);
if(host == NULL)
{
#ifdef WIN32
WSACleanup();
#endif
return false;
}
//Obtain the computer's IP
myIP.b1 = ((struct in_addr *)(host->h_addr))->S_un.S_un_b.s_b1;
myIP.b2 = ((struct in_addr *)(host->h_addr))->S_un.S_un_b.s_b2;
myIP.b3 = ((struct in_addr *)(host->h_addr))->S_un.S_un_b.s_b3;
myIP.b4 = ((struct in_addr *)(host->h_addr))->S_un.S_un_b.s_b4;
#ifdef WIN32
WSACleanup();
#endif
return true;
}
Use htonl, htons, ntohl, ntohs functions to convert between network and local byte orders.
Upvotes: 4
Reputation: 283614
There is no standard way to do this in C++, because C++ also runs on systems which have no network.
Each operating system has a different way to query local interface addresses. The most "portable" thing you can hope to find is a library that provides a single consistent interface with underlying implementations corresponding to all major operating systems.
Upvotes: 1