How to become a Python network programmer

Python Network Programming

Python offers two levels of access network services. :

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

What is a socket?

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

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 in or
  • Protocol: Generally not to be filled to zero by default.

Socket object (built-in) procedure

function description
Server socket
s.bind () Bind address (host, port) to the socket at AF_INET, in the form of a tuple (host, port) gives the address.
see lists () Start listening to TCP. backlog specified before the connection refuses, the operating system can set 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. Main 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 will return an error code if an error will throw an exception instead
Socket functions for public purposes
s.recv () If you receive TCP data, the data is returned as a string, specifying the maximum amount of data to be received bufsize. You can enter additional information about the message flag usually ignored.
s.send () Sending TCP data, sends the data chain to the socket connection. The return value is the number of bytes to send this number, which can be less than the sequence of bytes.
s.sendall () Complete sending of TCP data, complete sending of TCP data. It sends the data chain to the socket connection, but tries to send all of the data before returning. Successful return None, failure exception is thrown.
s.recvform () Receive UDP data () is similar to recv, but the return value (data, address). Where the data is a character string that contains the received data, address data sent socket address.
s.sendto () Send UDP data, send data to a socket, address is given in the form of (ipaddr, port) tuple remote address. The return value is the number of bytes sent.
S.CLOSE () Close the socket
s.getpeername () Specifies 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 operation on timeout time, timeout is a floating point number in seconds. No value does not time out. In general, timeout should only create one socket set because it can be used to operate the connection (such as connect ())
s.gettimeout () Specifies the value of the current timeout in seconds, if there is no set timeout, there is 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 is set to blocking mode (default value). Non-blocking mode, if you call recv () have no data to find, or send () call cannot send data immediately, it would cause socket.error exception.
s.makefile () Prepare a relevant document related to the socket

Simple example

The server

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 (host - Name, port)functionPort.

Next we call the method of the socket objects take.The procedure waits for the client connection andConnection objectback that represents connected to the client.

The full code is as follows:

#! / usr / bin / python # - * - 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.send ('欢迎 访问 本 教程!') 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 with the host for theHost namePort toport- Service provider.Once connected, the server can publish data, remember that after the operation has finished you must close the connection.

The full code is as follows:

#! / usr / bin / python # - * - coding: UTF-8 - * - # 文件 名 : import socket # 导入 socket 模块 s = socket.socket () # 创建 socket 对象 host = socket.gethostname ( ) # 获取 本地 主机 名 port = 12345 # 设置 端口 好 s.connect ((host, port)) print s.recv (1024) s.close ()

Now we also have to open the terminal, where the first connection leads to file:

$ python

The second port runs file:

$ python 欢迎 访问 本 教程!

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

连接 地址 : ('', 62461)

Python internet modules

Here are some important Python network programming module:

agreement Useful function Port number Python modules
HTTP Web access 80 httplib, urllib, xmlrpclib
NNTP Read and send news articles known as the "post" 119 nntplib
FTP File transfer 20 ftplib, urllib
SMTP Send e-mail 25 smtplib
POP3 Receiving mail 110 poplib
IMAP4 Read mail 143 imaplib
Telnet Command line 23 telnetlib
Ground squirrel Make 70 gopherlib, urllib

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