First, call the bind () function:
The kernel has three corresponding data structures for different sockets (raw/dgram/stream), namely, struct proto_ops global data structure. Its binding function pointer is assigned to the inet_bind () function. So when we call the bind () function, we call the inet_bind () function. This function will attempt to bind the corresponding socket to the specified port.
Second, when bind () is not called:
In the following cases, the kernel will call the inet_autobind () function, which, as the name implies, will automatically select an appropriate port for the relevant socket.
Call the connect () function on the socket.
Call the sendmsg () function.
In the inet_autobind () function, if the local port of the socket is 0:
For TCP IPV4/IPV6, inet_csk_get_port () will eventually be called to select the appropriate local port;
For UDP IPV4/IPV6, udp_v4_get_port () or udp_v6_get_port () will be called to select the appropriate local port;