How to disconnect UDP sockets in Python _python

Source: Internet
Author: User
Tags sin

A UDP socket can be connected to a specified address using the Connect system call. 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 an address. You can call connect again to connect to another place. But in Python, once you call connect, you're no longer able to return to the initial state of receiving data from any address!

This is the Python API limit, and there's no way to pass the Connect method to the Af_unspec address cluster (written in C code). C inside can do (code from here):

Copy Code code 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));
}

But since it's a Python limitation, take ctypes and get around, there's some trouble:

Copy Code code as follows:

From ctypes import Cdll, Create_string_buffer

def disconnect (sock):
libc = Cdll ("libc.so.6")
BUF = Create_string_buffer (a) # sizeof struct SOCKADDR_IN
Libc.connect (Sock.fileno (), buf, 16)

The value of the Af_unspec is 0, so it is possible to pass a full 0 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.