In Python, the disconnect UDP socket method is pythondisconnect.
You can use the connect system to call a UDP socket to connect to the specified address. Since then, this socket will only receive data from this address, and you can use the send system call to send data directly without specifying the address. You can call connect again to connect to other places. However, in Python, once connect is called, it will no longer be able to return to the initial state that can receive data from any address!
This is an API restriction for Python. It is impossible to pass the connect Method to the AF_UNSPEC address cluster (written in C code ). You can do this in C (the Code comes from here ):
Copy codeThe Code is as follows:
Int disconnect_udp_sock (int fd ){
Struct sockaddr_in sin;
Memset (char *) & sin, 0, sizeof (sin ));
Sin. sin_family = AF_UNSPEC;
Return (connect (fd, (struct sockaddr *) & sin, sizeof (sin )));
}
However, since it is a Python restriction, you can use ctypes to bypass it. Some troubles are as follows:
Copy codeThe Code is as follows:
From ctypes import CDLL, create_string_buffer
Def disconnect (sock ):
Libc = CDLL ("libc. so.6 ")
Buf = create_string_buffer (16) # sizeof struct sockaddr_in
Libc. connect (sock. fileno (), buf, 16)
The AF_UNSPEC value is 0, so you can pass a zero-length buffer as long as struct sockaddr_in to connect :-)