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

标签 c linux sockets nic

注意:问题已被编辑。

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

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

    2.根据https://www.cs.cmu.edu/~srini/15-441/F01.full/www/assignments/P2/htmlsim_split/node18.html ,当套接字绑定(bind)到 INADDR_ANY 时,它从所有接口(interface)接收数据包,但是当发送数据包时,(使用发送命令)它通过具有默认 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)发送数据包吗?如果 NIC 具有默认 IP 地址,我们可以这样做吗?

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

最佳答案

Is it possible to change a socket address after created?

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

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毫无区别地进行区分。绑定(bind)到 INADDR_ANY 的套接字从任何接口(interface)接收数据包。就 INADDR_ANY 而言,“any”和“all”之间没有区别。理解为“任何”要容易得多。

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 地址:任何 NIC。

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 如何工作,那就错了。

关于c - 套接字编程-更改套接字IP,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33005234/

相关文章:

c - 我们应该使用多个接受器套接字来接受大量连接吗?

node.js - 使用 Socket.io 连接到特定的服务器 IP

c - 读入文件,段错误

c++ - 对于客户端服务器程序,并行接收多个客户端连接请求的最佳方法是什么?

c - Segmentation Fault 错误由于添加了一个小的 2d 数组

C将数字列表读入多个数组

java - 将java程序转换为linux上的可执行文件

c++ - 解密无符号字符*

swift - 在 Swift 中创建的 CFSocket 不监听

linux - 如何在英特尔显卡上为 "monitor plugged"创建回调?