Python’s Standard Library :Networking
Python的标准库为创建网络服务和远程访问服务提供了一些模块。例如:ipaddress, socket, socketserver 等。
Python’s standard library comes complete with modules for creating network services, as well as for accessing existing services remotely. The ipaddress module includes class for validating, comparing, and otherwise operating on IPv4 and IPv6 network addresses. The low-level socket library provides direct access to the native C socket library, and can be used to communicate with any network service.
Finding Service Information
In addition to an IP address, each socket address includes an integer port number. Many applications can run on the same host, listening on a single IP address, but only one socket at a time can use a port at that address. The combination of IP address, protocol, and port number uniquely identifies a communication channel and ensures that messages sent through a socket arrive at the correct destination.
Some of the port numbers are pre-allocated for a specific protocol. For example, communication between email servers using SMTP occurs over port numbers 25 using TCP, and standardized names can be looked up with getservbyname().
The example codes are as follow:
import socket
from urllib.parse import urlparseURLS = ['http://www.python.org','https://www.mybank.com','ftp://prep.ai.mit.edu','gopher://gopher.micro.umn.edu','smtp://mail.example.com','imap://mail.example.com','imaps://mail.example.com','pop3://pop.example.com','pop3s://pop.example.com',
]for url in URLS:parsed_url = urlparse(url)port = socket.getservbyname(parsed_url.scheme)print('{:>6} : {}'.format(parsed_url.scheme, port))
Although a standardized service is unlikely to change ports, looking up the value with a system call instead of hard-coding it is more flexible when new services are added in the future.
The result is as follow:
D:\Python39\python.exe D:/My_Project/standard_library/socket_getservbyname.pyhttp : 80https : 443ftp : 21
gopher : 70smtp : 25imap : 143imaps : 993pop3 : 110pop3s : 995Process finished with exit code 0
To reverse the service port lookup, use getservbyport().
The example codes are as follows:
import socketfor port in [80, 443, 21, 70, 25, 143, 993, 110, 995]:url = '{}://example.com/'.format(socket.getservbyport(port))print(url)
The reverse lookup is useful for constructing URLs to services from arbitrary addresses.
The result is as follow:
D:\Python39\python.exe D:/My_Project/standard_library/socket_getservbyport.py
http://example.com/
https://example.com/
ftp://example.com/
gopher://example.com/
smtp://example.com/
imap://example.com/
imaps://example.com/
pop3://example.com/
pop3s://example.com/Process finished with exit code 0
To retrieve the number assigned to a transport protocol, use getprotobyname.
The example codes are as follow:
import socketdef get_constants(prefix):'''Create a dictionary mapping socket modulecontants to their names.'''return {getattr(socket, n): n for n in dir(socket)if n.startswith(prefix)}protocols = get_constants('IPPROTO_')for name in ['icmp', 'udp', 'tcp']:proto_num = socket.getprotobyname(name)const_naem = protocols[proto_num]print('{:>4} -> {:2d} (socket.{:<12} = {:2d})'.format(name, proto_num, const_naem,getattr(socket, const_naem)))
The values for protocol numbers are standardized, and defined as constants in socket with the prefix IPPROTO_.
The result is as follow:
D:\Python39\python.exe D:/My_Project/standard_library/socket_getprotobyname.py
icmp -> 1 (socket.IPPROTO_ICMP = 1)udp -> 17 (socket.IPPROTO_UDP = 17)tcp -> 6 (socket.IPPROTO_TCP = 6)Process finished with exit code 0