This article mainly introduces the disconnectUDP socket method in Python. This article uses the ctypes bypass method, for more information about UDP sockets, you can use the connect system 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 ):
The 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:
The 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 :-)