Methods for disconnectUDP socket in Python-Python tutorial

Source: Internet
Author: User
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 :-)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.