Setting the source IP for a UDP socket

后端 未结 4 1208
攒了一身酷
攒了一身酷 2020-11-27 04:10

I have a UDP socket that is bound to INADDR_ANY to listen to packets on all the IPs my server has. I\'m sending out replies through the same socket.

Right now the se

4条回答
  •  悲哀的现实
    2020-11-27 04:51

    I encountered the same problem recently.

    What I do to solve this problem is

    1. get the interface name from received packet
    2. bind socket to specific interface
    3. unbind socket

    Example:

      struct ifreq ifr;
      ...
      recvmsg(fd, &msg...)
      ...      
      if (msg.msg_controllen >= sizeof(struct cmsghdr))
        for (cmptr = CMSG_FIRSTHDR(&msg); cmptr; cmptr = CMSG_NXTHDR(&msg, cmptr))
          if (cmptr->cmsg_level == SOL_IP && cmptr->cmsg_type == IP_PKTINFO)
          {
            iface_index = ((struct in_pktinfo *)CMSG_DATA(cmptr))->ipi_ifindex;
          }
      if_indextoname(iface_index , ifr.ifr_name);
      mret=setsockopt(fd, SOL_SOCKET, SO_BINDTODEVICE, &ifr, sizeof(ifr));
    
      sendmsg(...);
    
      memset(&ifr, 0, sizeof(ifr));
      snprintf(ifr.ifr_name, sizeof(ifr.ifr_name), "");
      mret=setsockopt(fd, SOL_SOCKET, SO_BINDTODEVICE, &ifr, sizeof(ifr));
    

提交回复
热议问题