Search code examples
socketsudpposixbind

read() form an unbinded socket?


What happens if one reads from an unbinded socket? More specifically on an UDP socket?

If the socket has been used to send information the socket will be binded to a port (and address) and therefore we will be listening on that (addr, port), but if the socket is completely unbinded what is the expected behavior? How will that socket will respond to select/epoll in that case for read operation?


Solution

  • It's variously specified, or not specified.

    From man 7 udp (Linux):

    In order to receive packets, the socket can be bound to a local address first by using bind(2). Otherwise the socket layer will automatically assign a free local port out of the range defined by /proc/sys/net/ipv4/ip_local_port_range and bind the socket to INADDR_ANY.

    From MSDN recv() function:

    The local address of the socket must be known. For server applications, use an explicit bind function or an implicit accept or WSAAccept function. Explicit binding is discouraged for client applications. For client applications, the socket can become bound implicitly to a local address using connect, WSAConnect, sendto, WSASendTo, or WSAJoinLeaf.

    and

    WSAEINVAL: The socket has not been bound with bind, ...

    I cannot answer for BSD, Solaris, HP-UX, AIX, ...