简体   繁体   English

如何使用WinSock2和C获取连接的客户端的IP地址?

[英]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.

相关问题 如何使用c在winsock2中发送图像 - how to send an image in winsock2, using c 来自外部IP地址的Winsock2连接 - Winsock2 connection from an external IP address 如何使用c socket程序在报告中显示客户端的IP地址? - How do i display client's ip address in the report using c socket program? 为什么我没有在 C 中获得带有 Winsock2 程序的 BBC 服务器的主要 web 页面? - Why don't i get the main web page of BBC server with Winsock2 program in C? 如何使用 winsock2 库在 C 中发送程序当前工作目录? - How do you send a programs current working directory in C using the winsock2 library? 使用Winsock2和C缩短TCP连接的等待时间 - Shortening wait time for TCP connection using Winsock2 and C 如何在客户端服务器应用程序中异步发送文件?(在C中使用winsock2.h) - How can i send files asynchronously in a client-server application?(using winsock2.h, in C) 我怎样才能知道 C 中接口的 IP 地址? - How can I get to know the IP address for interfaces in C? C套接字编程:获取服务器绑定到的IP地址(IPv6或IPv4)和客户端连接到的地址? - C socket programming: get IP address (IPv6 or IPv4) server bounds to, and client connected to? 如何使用C获取站点IP地址 - How to get site ip address using c
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM