C语言 获取传入套接字连接的源地址
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2064636/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Getting the source address of an incoming socket connection
提问by David
I have a server with a incoming socket from a client.
I need the get the IP address of the remote client.
Tried searching google for in_addrbut it's a bit troublesome.
Any suggestions?
我有一个带有来自客户端的传入套接字的服务器。我需要获取远程客户端的 IP 地址。尝试用谷歌搜索,in_addr但有点麻烦。有什么建议?
回答by Eli Bendersky
You need the getpeernamefunction:
你需要的getpeername功能:
// assume s is a connected socket
socklen_t len;
struct sockaddr_storage addr;
char ipstr[INET6_ADDRSTRLEN];
int port;
len = sizeof addr;
getpeername(s, (struct sockaddr*)&addr, &len);
// deal with both IPv4 and IPv6:
if (addr.ss_family == AF_INET) {
struct sockaddr_in *s = (struct sockaddr_in *)&addr;
port = ntohs(s->sin_port);
inet_ntop(AF_INET, &s->sin_addr, ipstr, sizeof ipstr);
} else { // AF_INET6
struct sockaddr_in6 *s = (struct sockaddr_in6 *)&addr;
port = ntohs(s->sin6_port);
inet_ntop(AF_INET6, &s->sin6_addr, ipstr, sizeof ipstr);
}
printf("Peer IP address: %s\n", ipstr);
回答by Craig McQueen
Assuming you're using accept()to accept incoming socket connections, getpeername()isn't needed. The address information is available via the 2nd and 3rd parameters of the accept()call.
假设您正在使用accept()接受传入的套接字连接,getpeername()则不需要。地址信息可通过accept()调用的第二个和第三个参数获得。
Here is Eli's answer modified to do it without getpeername():
这是 Eli 的答案,修改为没有getpeername():
int client_socket_fd;
socklen_t len;
struct sockaddr_storage addr;
char ipstr[INET6_ADDRSTRLEN];
int port;
len = sizeof addr;
client_socket_fd = accept(server_socket_fd, (struct sockaddr*)&addr, &len);
// deal with both IPv4 and IPv6:
if (addr.ss_family == AF_INET) {
struct sockaddr_in *s = (struct sockaddr_in *)&addr;
port = ntohs(s->sin_port);
inet_ntop(AF_INET, &s->sin_addr, ipstr, sizeof ipstr);
} else { // AF_INET6
struct sockaddr_in6 *s = (struct sockaddr_in6 *)&addr;
port = ntohs(s->sin6_port);
inet_ntop(AF_INET6, &s->sin6_addr, ipstr, sizeof ipstr);
}
printf("Peer IP address: %s\n", ipstr);
回答by caf
Since you say it is an incoming connection from a client, as an alternative to getpeernameyou can just save the address that was returned by the accept()call, in the second and third parameters.
既然您说这是来自客户端的传入连接,那么作为替代方案,getpeername您可以将accept()调用返回的地址保存在第二个和第三个参数中。

