gpt4 book ai didi

sockets - 在 TCP 三向握手之前获取 INADDR_ANY 客户端套接字的源 IP 和端口?

转载 作者:可可西里 更新时间:2023-11-01 02:51:46 27 4
gpt4 key购买 nike

我在 Windows 7 上,在 connectSO_REUSEADDR 之前使用 bind,并将本地地址结构设置为 IP 地址 INADDR _ANY 和端口 0(零),以便让操作系统选择客户端套接字的源详细信息。

首先,我读到在连接到服务器之前无法获取源 IP,因为此时正在选择它并且多个地址可能有效。但是在连接之前选择了端口,那么有什么办法可以得到呢? (getsockname() 看起来不起作用)。

其次,关于源IP,有没有办法在数据包发送到服务器之前得到它?我需要操作系统选择源 IP 和它开始三向握手之间的具体时间。 connect() 函数控制着两者。

最佳答案

I'm on Windows 7, using bind before connect with SO_REUSEADDR

为什么在这种情况下使用 SO_REUSEADDR?你不需要它,它对你的尝试毫无意义。 SO_REUSEADDR 通常应该只用于监听 套接字,而不是连接 套接字。

setting the local address structure to IP address INADDR _ANY and port 0 (zero), in order to let the operating system select the source details for a client socket.

bind() client 套接字到 INADDR_ANY:0 是没有意义的。您可以(并且应该)完全省略这样的 bind() 并在 connect() 被调用之前保持套接字未绑定(bind)唯一你应该 bind() client 套接字的时候是你想将它绑定(bind)到 < em>特定 本地 IP 和/或端口。但在这种情况下你没有这样做,所以摆脱它。

Firstly, I've read that it's not possible to get the source IP before connecting to the server, since it's being chosen at this point and several addresses can be valid.

正确,除非您bind()特定 源 IP。

But the port is selected before the connection

如果套接字未绑定(bind),或者绑定(bind)到源 IP INADDR_ANY 和/或源端口 0,则源 IP 和源端口都由 connect() 选择。所以你在 connect() 选择它们之前没有机会查询任何一个值。

so is there a way to get it? (getsockname() looks like to not work).

getsockname() 正是您所需要的。请确保在 connect() 首先成功连接到服务器之前不要调用它。这在 getsockname() 中说明文档:

This call is especially useful when a connect call has been made without doing a bind first; the getsockname function provides the only way to determine the local association that has been set by the system.
...
The getsockname function does not always return information about the host address when the socket has been bound to an unspecified address, unless the socket has been connected with connect or accept (for example, using ADDR_ANY). A Windows Sockets application must not assume that the address will be specified unless the socket is connected. The address that will be used for the socket is unknown unless the socket is connected when used in a multihomed host. If the socket is using a connectionless protocol, the address may not be available until I/O occurs on the socket.

Secondly, about the source IP, is there a way to get it before a packet is sent to the server?

对于 TCP,您可以在 connect() 成功连接到服务器后立即使用 getsockname() 检索选定的源 IP。之前没有。

I need the specific time between the moment the OS selected the source IP and the moment it starts the three-way handshake.

无法确定该细节。任何套接字应用程序都不应该需要这些细节。为什么需要它?

关于sockets - 在 TCP 三向握手之前获取 INADDR_ANY 客户端套接字的源 IP 和端口?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29331726/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com