A PC can be connected to multiple networks at the same time (Internet, VM, VPN, etc), each with its own IP address, and you could initialize sockets on any of them at the same time and it would work. And more and more common, PCs are getting their Internet access from home router/ICS connections, not directly from Internet modems.
So what "real IP address" are you looking for? The PC can have multiple IP addresses, and they are all "real" as far as the OS cares.
If you just want to enumerate the available local IP addresses, you can use GetAdaptersInfo()
or GetAdaptersAddresses()
. DO NOT use gethostbyname()
to discover local IP addresses - that is not what it is meant for, and it can report false information!
I think the question you actually want to ask is - how do I find the IP of the Ethernet controller used to access the Internet - am I right?
For that, you will have to connect()
an unbound socket to an outside server that is running on the Internet, and if successful then you can use getsockname()
to find out which local IP address the OS bound the socket to, for example:
SOCKET sock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
sockaddr_in remoteaddr = {0};
remoteaddr.sin_family = AF_INET;
remoteaddr.sin_addr.s_addr = inet_addr("remote ip address");
remoteaddr.sin_port = htons(80);
if (connect(sock, (sock_addr*)&remoteaddr, sizeof(remoteaddr)) == 0)
{
sockaddr_in localaddr = {0};
int len = sizeof(localaddr);
getsockname(sock, (sock_addr*)&localaddr, &len);
// use localaddr as needed...
}
closesocket(sock);
But that is only going to tell you the IP address on the local PC. If you are behind a router/ICS, that is not going to be the same IP address that the Internet uses to send packets to your PC. To get that IP address, you can connect to and query an outside iplookup service, such as http://whatismyip.com, and see what IP address it reports back to you.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…