简体   繁体   中英

How can I get the connected host's IP address from a Windows Socket (C++)?

I've seen this asked before, but I never found an answer that worked. I need to get the explicit IP address (ie 123.456.789.100) and PORT number of the computer that my server is connected to in order to forward that info to other clients. I'm using WinSock2.h on Windows 7 (Home Premium), Visual Studio 2010 Professional - making a "C++ console application". This is a TCP connection. Here's my code so far:

sockaddr_in* addr = new sockaddr_in;
int addrsize = sizeof(addr);
getsockname(clientSock, (sockaddr*)addr, &addrsize);
char* ip = inet_ntoa(addr->sin_addr);
int port = addr->sin_port;
printf("IP: %s ... PORT:%d\n", ip, port);

This always gives me 205.205.205.205 for the IP, and 52685 for the PORT every time. I've tried alternatives, including gethostbyname, which works but I need the actual IP itself. I've also tried getpeername() in place of getsockname(), but the results were identical. I am behind a router, but I'm using both the server and client on the same machine so far.

Thanks in advance for any and all help!

getpeername() is the function you want to be using.

Some errors I see in your code:

1) You're allocating addr on the heap. No need to do that, just declare "sockaddr_in addr;" on the stack instead, and pass &addr (instead of addr) to your getpeername() call.

2) addrsize is being set to the size of a pointer (eg 4 or 8), not to the size of the actual sockaddr_in, which means that...

3) getsockname() is probably failing, but you don't know that because

4) You're not checking the return value of getsockname() to see if there was an error or not, which means that

5) The results you are seeing are just showing you whatever random garbage data was in (*addr) before the getsockname()/getpeername() call, because the call failed without ever writing anything to the addr struct.

6) Oh, one more thing... be sure to wrap your reference to addr.sin_addr in a ntohl() call, and your reference to addr.sin_port in a ntohs() call, or you'll get them in big-endian form when running on a little-endian (read: Intel-based) computer, which isn't what you want.

Yes, you were right, it was throwing an error and I haven't checked for it. Thank you very much, your solution worked. The final code that worked for me was as follows:

sockaddr_in addr;
int addrsize = sizeof(addr);
int result = getpeername(clientSock, (sockaddr*) &addr, &addrsize);
printf("Result = %d\n", result);
char* ip = inet_ntoa(addr.sin_addr);
int port = addr.sin_port;
printf("IP: %s ... PORT: %d\n", ip, port);

And that got me the correct results. I appreciate your help. Thanks!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM