问题描述
我正在编写简单的服务器/客户端,并尝试获取客户端IP地址并将其保存在服务器端,以确定哪个客户端应进入关键部分.我用Google搜索了好几次,但是找不到从袜子结构中获取IP地址的正确方法.
I'm writing simple server/client and trying to get client IP address and save it on server side to decide which client should get into critical section. I googled it several times but couldn't find proper way to get IP address from sock structure.
我相信这是在服务器接受客户端请求后从袜子结构获取IP的一种方法.更具体地讲,服务器执行后
I believe this is a way to get IP from sock struct after server accept request from client. More specifically in c after server execute
csock = accept(ssock, (struct sockaddr *)&client_addr, &clen)
谢谢
推荐答案
确定您正在使用IPV4,然后执行以下操作:
OK assuming you are using IPV4 then do the following:
struct sockaddr_in* pV4Addr = (struct sockaddr_in*)&client_addr;
struct in_addr ipAddr = pV4Addr->sin_addr;
如果您随后希望将IP地址作为字符串,请执行以下操作:
If you then want the ip address as a string then do the following:
char str[INET_ADDRSTRLEN];
inet_ntop( AF_INET, &ipAddr, str, INET_ADDRSTRLEN );
IPV6也很容易...
IPV6 is pretty easy as well ...
struct sockaddr_in6* pV6Addr = (struct sockaddr_in6*)&client_addr;
struct in6_addr ipAddr = pV6Addr->sin6_addr;
获取字符串几乎与IPV4相同
and getting a string is almost identical to IPV4
char str[INET6_ADDRSTRLEN];
inet_ntop( AF_INET6, &ipAddr, str, INET6_ADDRSTRLEN );
这篇关于如何从C中的袜子结构获取IP地址?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!