Latest web development tutorials

Python Network Programming

Python offers two levels of access network services. :

  • Low-level network services to support basic Socket, it provides a standard BSD Sockets API, you can access all of the methods of the underlying operating system Socket interface.
  • A high level of network service module SocketServer, it provides a central server class, you can simplify the development of the network server.

What is Socket?

Socket also known as "socket", the application is usually issued by a "socket" to the network request or response network request, so that the process between hosts or between a computer on can communicate.

socket () function

Python, we use the socket () function to create a socket, syntax is as follows:

socket.socket([family[, type[, proto]]])


  • family: the family can make a socket or AF_INET AF_UNIX
  • type: Socket type can be connection-oriented or connectionless into SOCK_STREAM or SOCK_DGRAM
  • protocol: Generally not fill defaults to zero.

Socket object (built-in) method

function description
Server socket
s.bind () Bind address (host, port) to the socket at AF_INET, in the form of a tuple (host, port) indicates the address.
s.listen () Start TCP listening. backlog specified before rejecting the connection, the operating system can suspend the maximum number of connections. This value is at least 1, most applications can be set to 5.
s.accept () Passive acceptance of TCP client connections (blocking) waiting for the arrival of
Client socket
s.connect () Active initialize TCP server connections. General address of the format of tuples (hostname, port), if the connection error, an error is returned socket.error.
s.connect_ex () connect () extended version of the function returns an error code when an error instead of throwing an exception
Socket functions public purposes
s.recv () Receive TCP data, the data is returned as a string, specify the maximum amount of data to be received bufsize. Provide additional information about the message flag can usually be ignored.
s.send () Send TCP data, sends the data string to the socket connection. The return value is the number of bytes to send, this number may be less than the string of bytes.
s.sendall () Complete sending TCP data, complete transmit TCP data. It sends the data string to the socket connection, but before returning will try to send all the data. Successful return None, failure exception is thrown.
s.recvform () Receiving UDP data () is similar to recv, but the return value is (data, address). Wherein the data is a string containing the received data, address data is sent socket address.
s.sendto () Send UDP data, send data to a socket, address is in the form of (ipaddr, port) tuple specified remote address. The return value is the number of bytes sent.
s.close () Close the socket
s.getpeername () Returns the connection socket remote address. 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) Set the value of a given socket option.
s.getsockopt (level, optname [.buflen]) The return value of the socket option.
s.settimeout (timeout) Set socket operation timeout period, timeout is a floating-point number, in seconds. None value indicates no time-out period. Generally, time-out period should just create a socket set, because they may be used to operate the connection (such as connect ())
s.gettimeout () Returns the value of the current time-out period, in seconds, if there is no set time-out period, returns None.
s.fileno () Returns a socket file descriptor.
s.setblocking (flag) If the flag is 0, the socket is set to non-blocking mode, otherwise the socket to blocking mode (the default value). Non-blocking mode, if you call recv () did not find any data, or send () call can not immediately send data, it would cause socket.error exception.
s.makefile () Create a relevant documents in connection with the socket

Simple example


We use the socket modulesocket function to create a socket object.socket object can call other functions to set up a socket service.

Now we can specify the services by callingbind (hostname, port) functionport (port).

Next, we call the acceptmethod of socket objects. The method waits for the client connection and returnconnectionobject that represents connected to the client.

The complete code is as follows:

# -*- coding: UTF-8 -*-
# 文件名

import socket               # 导入 socket 模块

s = socket.socket()         # 创建 socket 对象
host = socket.gethostname() # 获取本地主机名
port = 12345                # 设置端口
s.bind((host, port))        # 绑定端口

s.listen(5)                 # 等待客户端连接
while True:
    c, addr = s.accept()     # 建立客户端连接。
    print '连接地址:', addr
    c.close()                # 关闭连接


Next we write a simple client to connect to the service instances created above. Port number is 12345.

socket.connect (hosname, port) method opens a TCP connection to the host for thehostnameport toportservice providers.Once connected we can post-data from the server, remember, after the completion of the operation need to close the connection.

The complete code is as follows:

# -*- coding: UTF-8 -*-
# 文件名

import socket               # 导入 socket 模块

s = socket.socket()         # 创建 socket 对象
host = socket.gethostname() # 获取本地主机名
port = 12345                # 设置端口好

s.connect((host, port))
print s.recv(1024)

Now we even have to open the terminal, the first terminal performs file:

$ python

The second terminal performs file:

$ python 

This is our first and then open a terminal, you will see the following information is output:

连接地址: ('', 62461)

Python Internet modules

Here are some important module Python network programming:

protocol Useful function The port number Python Modules
HTTP Web access 80 httplib, urllib, xmlrpclib
NNTP Reading and posting news articles, known as the "post" 119 nntplib
FTP file transfer 20 ftplib, urllib
SMTP send email 25 smtplib
POP3 incoming mail 110 poplib
IMAP4 Get Mail 143 imaplib
Telnet Command Line twenty three telnetlib
Gopher Find information 70 gopherlib, urllib

More details can be found in the official website of the Python the Socket Library and the Modules .