C语言 从套接字描述符获取 IP 地址?

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

Get IP address from socket descriptor?

csocketsnetwork-programmingip

提问by michelemarcon

I've opened a TCP socket server (I've omitted a few stuff, it is taken from here

我已经打开了一个 TCP 套接字服务器(我省略了一些东西,它取自这里

sockfd = socket(p->ai_family, p->ai_socktype,
            p->ai_protocol))

Is it possible to get the IP address of the server from sockfd? If not where should I look?

是否可以从 sockfd 获取服务器的 IP 地址?如果不是我应该在哪里看?

EDIT: I want to know the address of the server (this is before any client connects).

编辑:我想知道服务器的地址(这是在任何客户端连接之前)。

回答by Joe

If you want to know who's at the other end of your socket you can use getpeernamein Linux. getsocknamewill tell you who you are. You decide what address you want your server to sit on initially though, at bindtime.

如果您想知道套接字的另一端是谁,您可以在 Linux 中使用getpeernamegetsockname会告诉你你是谁。不过,您可以在绑定时决定最初希望服务器位于哪个地址。

You may also find this SO question useful: bind socket to network interface

您可能还会发现这个问题很有用:将套接字绑定到网络接口

And the book "Unix Network Programming, vol 1", by W. Richard Stevens.

以及 W. Richard Stevens 所著的“Unix 网络编程,第 1 卷”一书。

回答by ugoren

You can't use the socket to get the server's address before a client connects, because it isn't known.

您不能在客户端连接之前使用套接字获取服务器地址,因为它是未知的。

In principle, a host may have multiple IPs. The IP used for a connection to a server is the one belonging to the interface, through which the connection arrived. Until a connection arrives, it isn't known.
Even if you have only one IP, connections may arrive from within the machine, in which case the address would be 127.0.0.1.

原则上,一台主机可以有多个IP。用于连接到服务器的 IP 是属于接口的 IP,连接通过该接口到达。在连接到达之前,它是未知的。
即使您只有一个 IP,连接也可能来自机器内部,在这种情况下,地址将是127.0.0.1.

So the listening socket has no information about the IP.
You'll need to find what interfaces the machine has, and what's their IPs.

所以监听套接字没有关于 IP 的信息。
您需要找到机器有哪些接口,以及它们的 IP 是什么。

回答by Davide Berra

The address of the server is up to you.

服务器的地址由您决定。

Depends on which parameters are passed to the bind()function.

取决于传递给bind()函数的参数。

You can specify a single ipor bind your socket to every address of your host.

您可以指定一个single ip或将您的套接字绑定到您主机的每个地址。

Look at the Bind man page

查看绑定手册页

回答by alk

The address of the server is the one that was passed to the successfull call to bind()(as shown in the source you linked).

服务器的地址是传递给成功调用的地址bind()(如您链接的源所示)。