[英]How can I get the connected client's IP address using WinSock2 and C?
I want to get the IP address of the client who's just connected into my server running WinSock2. 我想获取刚刚连接到运行WinSock2的服务器的客户端的IP地址。 I'm using C. 我正在使用C。
You could get the client's IP-address and port via the call to accept()
. 您可以通过调用accept()
获得客户端的IP地址和端口。
Just pass in the appropriate data into the last two parameters. 只需将适当的数据传递到最后两个参数即可。
struct sockaddr_in sa = {0}; /* for TCP/IP */
socklen_t socklen = sizeof sa;
... = accept(..., (struct sockaddr *) &sa, &socklen);
For details please read here . 有关详细信息, 请在此处阅读 。
Have not done it myself, but take a look at getpeername . 我自己还没有做过,但是看看getpeername 。 Looks like this is what you need. 看起来这就是您所需要的。
This work for me on winsock2 . 这为我在winsock2上工作。 No need of getpeername 无需getpeername
SOCKET newConnection;
SOCKADDR_IN addr;
int addrlen = sizeof(addr);
newConnection = accept(sListen, (SOCKADDR*)&addr, &addrlen);
char *ip = inet_ntoa(addr.sin_addr);
printf("Accepted Connection from : %s", ip);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.