Basic socket module in Python
November 6, 2016 at 2:48 am #3439
- Super Member
- Sockets for specific network protocols (such as TCP / IP, ICMP / IP, UDP / IP , etc.) suite of applications on the network providers portable object for the current standard.
They allow the program to accept and carry out the connection, such as sending and receiving data. In order to establish a communication channel, each endpoint network communications have a socket object is extremely important.
BSD UNIX socket as part of the core of the system, and they are also used by many other UNIX-like operating systems, including Linux adopted.
Many non-BSD UNIX systems (eg ms-dos, windows, os / 2, mac os and most mainframe environments) provide support for the socket to form the library.
- The three most popular socket type: stream, datagram, and raw.
- Socket module is a very simple object-based interface that provides access to low-level BSD-style sockets network.
The module can be implemented using client and server sockets.
To establish a simple and streaming server has TCP sockets in python, you need to use the socket module.
Use functions and class definitions contained in the module can be generated by the network communication program.
socket (family, type [, protocol]) : Creates a socket using the given address family, socket type, protocol number (defaults to 0).
Socket type Description socket.AF_UNIX Can only be used for a single Unix system inter-process communication socket.AF_INET Network communication between servers socket.AF_INET6 Ipv6 socket.SOCK_STREAM Flow socket for TCP socket.SOCK_DGRAM Datagram type for UDP socket.SOCK_RAW The original socket, ordinary socket can not handle ICMP, IGMP and other network packets, and SOCK_RAW can; Secondly, SOCK_RAW can also deal with special IPv4 packets; In addition, the use of raw socket, through IP_HDRINCL socket The option constructs an IP header by the user. socket.SOCK_SEQPACKET Reliable continuous packet service create TCP Socket: s=socket.socket(socket.AF_INET,socket.SOCK_STREAM) create UDP Socket: s=socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
- TCP send data, a good TCP connection has been established, so do not need to specify the address. UDP is for connectionless, each send to specify who is to whom.
- The server and client can not directly send lists, tuples, dictionaries. String repr (data) is required.
Socket Function Description Server socket function s.bind(address) Bind the socket to the address, AF_INET, in tuples (host, port) in the form of address. s.listen(backlog) Start listening for TCP incoming connections. Backlog Specifies the maximum number of connections that the operating system can suspend before the connection is refused. The value is at least 1, most of the application set to 5 on it. s.accept() Accepts the TCP connection and returns (conn, address), where conn is the new socket object that can be used to receive and send data. Address is the address of the connecting client. Client socket function s.connect(address) The socket connected to address. General address format for the tuple (hostname, port), if the connection error, return socket.error error. s.connect_ex(adddress) This function and connect (address) are the same, but the success of return 0, failed to return errno value. Public socket function s.recv(bufsize[,flag]) Accepts data for TCP sockets. The data is returned as a string, and bufsize specifies the maximum amount of data to be received. Flag Provides additional information about a message, which can usually be ignored. s.send(string[,flag]) Send TCP data. Sends the data in string to the connected socket. The return value is the number of bytes to be sent, which may be less than the byte size of the string. s.sendall(string[,flag]) Complete sending of TCP data. Sends the data from the string to the connected socket, but attempts to send all data before returning. Success returns None, failure throws an exception. s.recvfrom(bufsize[.flag]) Accepts UDP socket data. Similar to recv (), but the return value is (data, address). Where data is the string containing the received data and address is the socket address of the sending data. s.sendto(string[,flag],address) Send UDP data. The data is sent to the socket, address is the form (ipaddr, port) tuple, specify the remote address. The return value is the number of bytes sent. s.close() Close the socket. s.getpeername() Returns the remote address of the connected socket. The return value is usually a tuple (ipaddr, port). s.getsockname() Returns the socket’s own address. Usually a tuple (ipaddr, port) s.setsockopt(level,optname,value) Sets the value of the given socket option. s.getsockopt(level,optname[.buflen]) Returns the value of the socket option. s.settimeout(timeout) Sets the timeout period for socket operations, where timeout is a floating-point number in seconds. A value of None indicates no time-out period. In general, the timeout period should be set when the socket is just created, as they may be used for connected operations (such as connect ()) s.gettimeout() Returns the value of the current timeout, in seconds, or None if no timeout period has been set. s.fileno() Returns the file descriptor for the socket. s.setblocking(flag) If flag is 0, the socket is set to nonblocking mode, otherwise the socket is set to blocking mode (the default). In nonblocking mode, if no data is found by calling recv (), or the send () call can not send data immediately, a socket.error exception is thrown s.makefile() Creates a file that is associated with the socket
How to create socket in python
- TCP server
Create a socket that binds the socket to the local IP and port
socket.socket(socket.AF_INET,socket.SOCK_STREAM) , s.bind()Start listening for connections
Accept the client’s connection request
Receives the incoming data, and sent to the other data
s.recv() , s.sendall()
After the transfer is complete, close the socket
- TCP Client
Create a socket to connect to the remote address
socket.socket(socket.AF_INET,socket.SOCK_STREAM) , s.connect()
Connect to send data and receive data
After the transfer is complete, close the socket
- Server codeimport socket
print(‘tcpServer listen at: %s:%s\n\r’ %(HOST,PORT))
print(‘%s:%s connect’ %client_addr)
if not recv:
print(‘[Client %s:%s said]:%s’ % (client_addr,client_addr,recv))
client_sock.send(‘tcpServer has received your message’)
- Client Codeimport socket
print(‘[tcpServer said]: %s’ % recv)
No system is truly secure!
You must be logged in to reply to this topic.