Python‘s Standard Library :Networking

简介: Python‘s Standard Library :Networking

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

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

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 urlparse


URLS = [
    '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.py
  http  : 80
 https  : 443
   ftp  : 21
gopher  : 70
  smtp  : 25
  imap  : 143
 imaps  : 993
  pop3  : 110
 pop3s  : 995

Process finished with exit code 0

To reverse the service port lookup, use getservbyport().

The example codes are as follows:

import socket

for 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

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 socket

def get_constants(prefix):
    '''Create a dictionary mapping socket module
    contants 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
相关文章
|
Python
python pyinstaller “Cannot find the MXNet library“ libmxnet.dll #文件包缺失
python pyinstaller “Cannot find the MXNet library“ libmxnet.dll #文件包缺失
155 0
|
4月前
|
数据安全/隐私保护 Python
Python 解压还密码的压缩文件 LookupError: Couldn't find path to unrar library.
Python 解压还密码的压缩文件 LookupError: Couldn't find path to unrar library.
79 2
|
7月前
|
存储 C++ Python
Python 教程之运算符(8)—— Inplace vs Standard 运算符
Python 教程之运算符(8)—— Inplace vs Standard 运算符
45 0
|
7月前
|
iOS开发 MacOS Python
完美解决 Python library not found: libpython3.10m.dylib, Python3, .Python, libpython3....
完美解决 Python library not found: libpython3.10m.dylib, Python3, .Python, libpython3....
175 0
|
7月前
|
Shell iOS开发 MacOS
完美解决 Python library not found: libpython3.10m.dylib, Python3, .Python, lib...
完美解决 Python library not found: libpython3.10m.dylib, Python3, .Python, lib...
184 0
|
存储 C++ Python
Python 教程之运算符(8)—— Inplace vs Standard 运算符
Python 教程之运算符(8)—— Inplace vs Standard 运算符
61 0
|
存储 数据格式 Python
第24天:Python Standard Library 02
第24天:Python Standard Library 02
144 0
|
人工智能 安全 测试技术
书籍:掌握Python的网络和安全 Mastering Python for Networking and Security - 2018.pdf
简介 掌握Python的网络和安全 掌握Python脚本以构建网络并执行安全操作。越来越明显的是,安全性是IT基础架构的一个关键方面。数据泄露是一个重大的安全事件,通常只是通过黑客攻击简单的网络线路来实现。
|
16天前
|
人工智能 数据可视化 数据挖掘
探索Python编程:从基础到高级
在这篇文章中,我们将一起深入探索Python编程的世界。无论你是初学者还是有经验的程序员,都可以从中获得新的知识和技能。我们将从Python的基础语法开始,然后逐步过渡到更复杂的主题,如面向对象编程、异常处理和模块使用。最后,我们将通过一些实际的代码示例,来展示如何应用这些知识解决实际问题。让我们一起开启Python编程的旅程吧!
下一篇
DataWorks