UDP and socket functions (binding ports)

  

UDP is a connectionless protocol, so the socket function connect seems to have no meaning for UDP, but this is not the case.

A socket has several properties, including protocol, local address/port, destination address/port.

For UDP, the socket function establishes a socket; the bind function specifies the local address/port (including ADDR_ANY, which is compatible with all local network interfaces); connect can be used to indicate the destination address/port;

Generally speaking, after the UDP client establishes the socket, it will directly send data using the sendto function. The destination address/port needs to be specified in the parameters of the sendto function. If a UDP client first uses the connect function to specify the destination address/port after setting up the socket, then the send function can also be used to send data. Because the send function already knows the address/port of the other party, this information can also be obtained by using getsockname.

After the UDP client establishes the socket, it will send data directly using the sendto function. It also implies an operation, that is, before sending the data, UDP will first select a separate UDP port for the socket. Between 1024 and 5000), the socket is set to the bound state. If a UDP client first uses the bind function to indicate the local address/port after setting up the socket, it is also possible to force UDP to use the specified port to send data. (In fact, UDP doesn't matter the server and the client, the boundaries here are blurred.)

The UDP server can also use connect. As mentioned above, connect can be used to indicate the destination address/port; this will result in The server only accepts requests from a specific host.

Copyright © Windows knowledge All Rights Reserved