如何从c中的sock结构获取IP地址? [英] How to get ip address from sock structure in c?

查看:30
本文介绍了如何从c中的sock结构获取IP地址?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写简单的服务器/客户端并尝试获取客户端 IP 地址并将其保存在服务器端以决定哪个客户端应该进入临界区.我用谷歌搜索了好几次,但找不到从袜子结构中获取 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.

我相信这是一种在服务器接受客户端请求后从 sock 结构中获取 IP 的方法.更具体地说,在服务器执行后的 c 中

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中的sock结构获取IP地址?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆