套接字编程-更改套接字IP

Socket Programming- Change Socket IP

注意:问题已编辑。

我有几个关于伯克利套接字编程的问题:

  1. 是否可以在绑定后更改套接字地址?如果是这样 - 这样做的 C 命令是什么?

    2.According到https://www.cs.cmu.edu/~srini/15-441/F01.full/www/assignments/P2/htmlsim_split/node18.html,当套接字绑定到INADDR_ANY时,它从所有接口接收数据包,但是当发送数据包时,(使用sent命令)它发送通过具有默认 IP 的单个 NIC。

    如果我理解正确——如果服务器有两个活动的 NIC,具有不同的 IP,那么带有 INADDR_ANY 参数的套接字可以接收 dst IP=x 的数据包并发送 src IP= 的数据包y,其中 x 不是 y。这可能会导致问题,例如在 TCP 连接中,另一个目标中的套接字将接收数据包,但由于目标 IP 不是预期的 IP 而将其丢弃。

    这是真的吗?如果是这样,这是否意味着服务器程序没有在有(两个或更多)具有不同 IP 的活动 NIC 的地方使用 INADDR_ANY?

  2. 假设默认IP的网卡造成瓶颈。我们可以更改套接字选项,以便通过另一个 NIC(而不是以前的 NIC)发送数据包吗?如果 NIC 具有默认 IP 地址,我们可以这样做吗?

  3. 我们可以通过一个网卡发送数据包,并将IP目标设置到另一个网卡吗? (即NIC1只会发送数据包,NIC2只会接收数据包)

Is it possible to change a socket address after created?

套接字在创建时没有要更改的 IP 地址。他们在绑定时得到一个。

If so- What are the C commands to do so?

Berkeley Sockets API 函数bind()connect()

When a socket is bind to INADDR_ANY, it receives packets from all interfaces, but sends through a single NIC with the default IP.

没有。在每种情况下,它都会通过到达目标所需的任何 NIC 发送数据包。

Your cited source无差别地画了个区分。绑定到 INADDR_ANY 的套接字从任何接口接收数据包。就INADDR_ANY而言,'any'和'all'没有区别。 'any' 更容易理解。

If I understand correctly- if a server has two active NICs, with different IPs, then a socket with the INADDR_ANY parameter can receive a packet with dst IP=x and send a packet with src IP=y, where x is not y

没有。它发送与客户端最初连接的源地址相同的数据包。这是定义连接的一部分。

This can cause problems, for example in TCP connections, where the socket in the other destination is will receive the packet, but will drop it due as the dest IP is not the one expected.

没有。数据包中的目的地是客户端的 IP 地址。否则它甚至不会到达那里。这纯属无稽之谈。如果您指的是源 IP,请参见上文。

Is it true?

没有

And if so- does it means that server programs are NOT using INADDR_ANY where there are (two or more) active NICs with different IPs?

没有。 INADDR_ANY 就是它所说的意思。 任意 IP 地址:任意网卡。

Suppose the NIC of the default IP causes bottleneck. Can we change the socket options so that the packets will be send through another NICs (and not the previous NIC)?

否,但您可以更改 IP 路由表。

Can we do so if the NICs have the default IP address?

其中只有一个可以有默认IP地址。这个问题没有意义。

Can we send packets through one NIC, and set the destination to another NIC?

仅当您发送给自己时。否则这个问题就没有意义。

(from your citation) When sending, a socket bound with INADDR_ANY binds to the default IP address, which is that of the lowest-numbered interface

我希望这是指所描述的任何模拟器。如果它是为了描述 TCP 的工作原理,那就错了。