简体   繁体   English

套接字与通配符ip绑定

[英]Socket bind with wildcard ip

I have a created a UDP socket and bind that socket to inaddr_any (0.0.0.0) and and some well known port number. 我创建了一个UDP套接字,并将该套接字绑定到inaddr_any (0.0.0.0)和一些众所周知的端口号。 As per my understanding this socket can receive data over all the interfaces of the machine over the specified port number. 据我了解,此套接字可以通过指定端口号通过计算机的所有接口接收数据。 But When i will call send() it will use the default IP address as the source address. 但是当我将调用send() ,它将使用默认IP地址作为源地址。

  • How is the default IP address chosen? 如何选择默认IP地址?
  • If I want to use some other interface (other than the default) for sending the data, how can this be done? 如果我想使用其他接口(默认接口除外)来发送数据,该怎么做?

Context of the problem: 问题的上下文:

I am implementing LDP protocol. 我正在实现LDP协议。 It can have many hello adjacencies. 它可以具有许多问候关系。 Thus i am creating a server to recv data from the other interfaces of the router. 因此,我正在创建一个服务器来从路由器的其他接口接收数据。 Once the hello adjacency is formed, then hello messages are to sent be on the specific interface over UDP over which the hello adjacency is created. 一旦形成了邻接关系,就将在通过该接口创建UDP的UDP上的特定接口上发送问候消息。

The default IP address is chosen based on the network the packet is sent to. 根据数据包发送到的网络选择默认IP地址。 For example if you have two interfaces, one connected to network A and the other connected to network B, if you send a packet to network B the packet will be sent with the IP address of the second interface. 例如,如果您有两个接口,一个连接到网络A,另一个连接到网络B,则如果您向网络B发送数据包,则将使用第二个接口的IP地址发送数据包。 For this reason, most of the time you don't have to worry about it . 因此,大多数时候您不必担心它

If you have two network interfaces connected to the same network, you can bind the socket to the address of one of them, and the packet will go out with that address. 如果您有两个连接到同一网络的网络接口,则可以bind套接字bind到其中一个的地址,数据包将与该地址一起发送出去。 For example, this will bind an IP socket to 192.168.122.1 , if allowed by the network stack: 例如,如果网络堆栈允许,这会将IP套接字绑定到192.168.122.1

struct sockaddr_in addr;
addr.sin_family = AF_INET;
addr.sin_addr.s_addr = inet_addr("192.168.122.1");
addr.sin_port = 0;
if (bind(s, (struct sockaddr*) &addr, sizeof addr) == -1) {
    perror("bind");
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM