Example sharing of UDP port multiplexing in Python's socket programming process

Source: Internet
Author: User
about Port Multiplexing

A socket cannot bind multiple ports at the same time, if the client wants to bind the port number, be sure to call the Send information function before binding (BIND) port, because in the Send information function (sendto, or write), the system will automatically assign a random port number to the current network program, This is equivalent to randomly binding a port number, which will only be allocated once, the communication will be at this random port to communicate, we then bind the port number, the binding fails. If we bind before the Send Message function (sendto, or write), the program will send the message with the port number that we bound, and no more randomly assign a port number. In fact, by default, if a socket for a network application is bound to a port, the port cannot be used by another socket. So how do you get two sockets to bind a port successfully? This will require a port to be reused. Port multiplexing allows an application to bind N sockets to a port without error.
The port multiplexing can communicate on the open port of the system, only character matching of the input information, no interception and copying of the network data, so the transmission performance of the network data is not affected at all.
However, it is important to note that after establishing a connection, the service-side program consumes very little system resources and the controlled side will not be aware of the system performance, usually used by backdoor Trojans.
In the implementation of Winsock, the binding to the server can be multi-binding, in determining the use of multi-binding who, according to a principle of who is the most specific to the specification of who will pass the package to whom, and there is no permission points, that is, the low-level permissions of the user can be re-bound in the high-level permissions such as This is a very significant security risk.

Python solves UDP port multiplexing issues
Always feel that the UDP protocol is very simple, but today's problem makes me feel that the foundation of the network is really profound.

Talk less and see the problem. Due to the need of the Protocol, I have to implement a UDP client and server side, and read and write data from the same port.

Initially dismissed, nothing is to use two sockets, a listener and read data from this port (the server side uses the twisted), the other to the port to write data, Python implementation as long as 10 lines of code.

def startserver (queue, port):   reactor.listenudp (port, Dhtresponsehandler (queue))   Reactor.run () def Sendudpmsg (self, addr, msg):   Sockethandler = Socket.socket (socket.af_inet, socket. SOCK_DGRAM)   Sockethandler.bind (("", Self.port)   sockethandler.sendto (msg, addr)   

Due to write data to the same port, so the client must have bind, but after the run found that the server bind the port, the client runtime will error

Copy the Code code as follows:

Error: [Errno 10048] Only one usage of each socket address (protocol/network address/port) is normally permitted


Generally this error occurs because multiple sockets cannot bind the same address at the same time
Because the foundation is not solid enough, I started the crazy search, found that some people say port multiplexing problem, so-called Port Multiplexing, refers to a socket to release a port after a wait_time, and another socket if bind will be error. Although my problem is not exactly the same, but I was ecstatic to use. That is, before client bind, add the following sentence

But still the error:

Copy the Code code as follows:


Error: [Errno 10013] An attempt is made to access a socket-in-a-type forbidden by its access permissions


(Incidentally, there is another parameter called So_reuseport, that is, multiplexing port, there is another called so_exclusiveaddruse, that is not allowed to reuse the port, the other socket parameters are many, you can refer to winsockhttp:// Msdn.microsoft.com/en-us/library/aa924071.aspx or a socket under Unix)
This 10013 error let me baffled the solution, search, there are two main explanations, some people say it is necessary to upgrade the application permissions for the administrator, I use the Eclipse+pydev, upgrade the eclipse permissions are useless, In fact, to modify the permissions of the Python.exe, the method is to right-click on this program, the compatibility column as a system administrator to run, some people say that the other program address or port conflicts. But I've been tested and found out.

In addition, the runtime found that the server side of the twisted must be in the main thread, otherwise it will be reported signal must be in the main thread to accept the error, but twisted reactor a run up blocked.

In the twisted document to turn to, there is a kind of UDP called connected UDP, perverted bar, so-called connected UDP, is only to send and receive data to an address, it seems to be possible, but does not meet the data can be received to multiple addresses.

Finally in an article to say that need two ports are set to reuse, so I try to re-write a server, with the previous client, running well, completely error-free

Well, it seems that the problem in the call twisted, do not know if he has such a setting, go in to this part of the code to turn over, can not find such parameters set.

Class Port (abstract. FileHandle): Def __init__ (self, port, Proto, Interface= ", maxpacketsize=8192, Reactor=none):" "" Initi     Alize with a numeric port to listen on.     "" "Self.port = port Self.protocol = Proto Self.readbuffersize = maxpacketsize Self.interface = interface Self.setlogstr () self._connectedaddr = None abstract. Filehandle.__init__ (self, reactor) Skt = Socket.socket (self.addressfamily, self.sockettype) Addrlen = _iocp.maxad Drlen (Skt.fileno ()) Self.addressbuffer = _IOCP. Allocatereadbuffer (Addrlen) # WSARecvFrom takes an int self.addresslengthbuffer = _IOCP. Allocatereadbuffer (struct.calcsize (' I ')) def startlistening (self): "" "Create and bind my socket, and      Begin listening on it. This was called on Unserialization, and must was called after creating a server to begin listening on the specified port     . "" "Self._bindsocket () Self._connecttoprotocol () def createsocket (sELF): Return Self.reactor.createSocket (self.addressfamily, Self.sockettype) def _bindsocket (self): try: Skt = Self.createsocket () skt.bind ((Self.interface, self.port)) except Socket.error, le:raise error.  Cannotlistenerror, (Self.interface, Self.port, le) # Make sure so if we listened on Port 0, we update this to #     Reflect what the OS actually assigned us. Self._realportnumber = Skt.getsockname () [1] log.msg ("%s starting on%s"% (Self._getlogprefix (self.protocol)  , self._realportnumber)) self.connected = True Self.socket = Skt Self.getfilehandle = Self.socket.fileno

Does it mean that twisted does not offer such a function at all? Finally in the multicast into such a paragraph, that is, the multicast situation is to support the address reuse, hands-on measurement.

Class Multicastport (Multicastmixin, Port): "" "   UDP Port that supports multicasting.    " " Implements (interfaces. Imulticasttransport)     def __init__ (self, port, Proto, Interface= ", maxpacketsize=8192,          Reactor=none, Listenmultiple=false):     port.__init__ (self, Port, Proto, interface, MaxPacketSize, reactor)     Self.listenmultiple = Listenmultiple     def createsocket (self):     Skt = Port.createsocket (self)     if Self.listenmultiple:       skt.setsockopt (socket. Sol_socket, SOCKET. SO_REUSEADDR, 1)       if hasattr (socket, "So_reuseport"):         skt.setsockopt (socket. Sol_socket, SOCKET. So_reuseport, 1)     

Change the server side to the following code, run it through!

Feeling a lot, the bottom of the knowledge is more important, floating sand building is dangerous.

  • 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.