0

When we bind a UDP server socket (Ip / port) to a special IP address INADDR_ANY - all interfaces avaliable in the system will be used for port PORT.

Now actually I am in need to find the MTU of the interface when a client gets connected - so I need to find the interface details to which a client has connected to it.

I tried to make use of getsockname API but it returned "0.0.0.0". How can I get the actual IP of the interface to which a client has gotten connected?

sshashank124
  • 31,495
  • 9
  • 67
  • 76
Programmer
  • 8,303
  • 23
  • 78
  • 162
  • 1
    You can't get it from the socket, because there isn't one for the socket, and there is no 'client connected' either. If your system supports it you may be able to get the destination addess of the incoming *datagram,* however. – user207421 Jan 03 '20 at 07:17
  • You could just enumerate all available interfaces, get the MTU for each, and use one that seems suitable (possibly the smallest one, depending on your use-case). – Some programmer dude Jan 03 '20 at 07:19

1 Answers1

4

There is no connection in UDP, that is why you can't use getsockname() the way you want.

If you want to know which interface receives each datagram when bound to INADDR_ANY, you can enable the IP_PKTINFO option on the socket and then use recvmsg() rather than recvfrom() to read the datagrams. The msghdr struct that recvmsg() populates on output can be used to determine the receiving interface. See the cmsg macros for more details.

See Get destination address of a received UDP packet

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770