C语言 如何从c中的sock结构获取IP地址?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3060950/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 05:41:11  来源:igfitidea点击:

How to get ip address from sock structure in c?

csocketsip-address

提问by REALFREE

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

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

csock = accept(ssock, (struct sockaddr *)&client_addr, &clen) 

Thanks

谢谢

回答by Goz

OK assuming you are using IPV4 then do the following:

好的,假设您使用的是 IPV4,然后执行以下操作:

struct sockaddr_in* pV4Addr = (struct sockaddr_in*)&client_addr;
struct in_addr ipAddr = pV4Addr->sin_addr;

If you then want the ip address as a string then do the following:

如果您希望将 IP 地址作为字符串,请执行以下操作:

char str[INET_ADDRSTRLEN];
inet_ntop( AF_INET, &ipAddr, str, INET_ADDRSTRLEN );

IPV6 is pretty easy as well ...

IPV6也很容易...

struct sockaddr_in6* pV6Addr = (struct sockaddr_in6*)&client_addr;
struct in6_addr ipAddr       = pV6Addr->sin6_addr;

and getting a string is almost identical to IPV4

并且获取字符串几乎与 IPV4 相同

char str[INET6_ADDRSTRLEN];
inet_ntop( AF_INET6, &ipAddr, str, INET6_ADDRSTRLEN );

回答by Misha

The easier and correct way for extracting IP address and port number would be:

提取 IP 地址和端口号的更简单和正确的方法是:

printf("IP address is: %s\n", inet_ntoa(client_addr.sin_addr));
printf("port is: %d\n", (int) ntohs(client_addr.sin_port));

The SoapBox's accepted answer won't be correct for all architectures. See Big and Little Endian.

SoapBox 接受的答案并不适用于所有架构。请参阅大端和小端

回答by SoapBox

Assuming client_addris a struct sockaddr_in(which it usually is). You can get the IP address (as a 32-bit unsigned integer) from client_addr.sin_addr.s_addr.

假设client_addr是一个struct sockaddr_in(通常是)。您可以从client_addr.sin_addr.s_addr.

You can convert it to a string this way:

您可以通过以下方式将其转换为字符串:

printf("%d.%d.%d.%d\n",
  int(client.sin_addr.s_addr&0xFF),
  int((client.sin_addr.s_addr&0xFF00)>>8),
  int((client.sin_addr.s_addr&0xFF0000)>>16),
  int((client.sin_addr.s_addr&0xFF000000)>>24));