Python‘s Standard Library :Networking

news/2024/12/29 0:35:06/

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

http://www.ppmy.cn/news/47427.html

相关文章

JAVA面试宝典: SpringCloud知识点(通俗易懂易背)

1、什么是 Spring Cloud&#xff1f; Spring Cloud 是基于 Spring Boot 的微服务架构开发工具箱&#xff0c;提供了在分布式系统中构建可靠的、弹性的、灵活的应用所需的大多数工具。Spring Cloud 中包含的子项目如下&#xff1a; Spring Cloud Config&#xff1a;配置管理工具…

STL :双端队列容器 Deque

Deque #include<deque> using namesace std; 双端队列容器 &#xff1a;双向开口的连续线性空间&#xff1b; 擅长尾部和头部添加或删除元素&#xff1a;常数阶&#xff1b; 存储元素并不能保证所有元素都存储到连续的内存空间中&#xff1b; deque 是动态的以分段…

系统需求分析

系统需求分析 需求分析是软件生存周期中相当重要的一个阶段。由于开发人员熟悉计算机但不熟悉应用 领域的业务&#xff0c;用户熟悉应用领域的业务但不熟悉计算机&#xff0c;因此对于同一个问题&#xff0c;开发人员和用 户之间可能存在认识上的差异。在需求分析阶段&#xff…

java记录-lambda表达式、接口应用、方法引用

基本形式 (str)->{System.out.println(str) };调用作为参数的接口实例的方法 1、用一个类实现接口&#xff0c;然后使用该类实例调用方法 2、匿名内部类 3、在 接口&#xff08;不能是抽象类&#xff09; 有且只有一个抽象方法时&#xff0c;可以使用lamda表达式来重写这个…

蓝桥 卷“兔”来袭编程竞赛专场-07明码加密 题解

赛题介绍 挑战介绍 清末&#xff0c;电报技术进入中国。上海大北水线电报公司在 1871 年选用了六千八百九十七个汉字&#xff0c;代以四码数字&#xff0c;编写成了中国最早的电报明码本。为了传输的内容可以保密&#xff0c;又设计出了将明码本加密的方法&#xff0c;于是就…

华为OD机试真题(Java),最小步骤数(100%通过+复盘思路)

一、题目描述 一个正整数数组 设为nums&#xff0c;最大为100个成员&#xff0c;求从第一个成员开始正好走到数组最后一个成员所使用的最小步骤数。 要求&#xff1a; 第一步 必须从第一元素起 且 1<第一步步长<len/2 (len为数组长度)&#xff1b;从第二步开始只能以所…

Junit概述和快速入门

单元测试概述 在程序中&#xff0c;一个单元可以是一个完整的模块&#xff0c;但它通常是一个单独的方法或者程序 在面向对象的编程中&#xff0c;一个单元通常是整个界面&#xff0c;例如类&#xff0c;但可能是单个方法 JUnit是一个java编程语言的单元测试框架 通过先为最…

从头创建一个新的浏览器,这合理吗?

从头构建一个新浏览器&#xff1f;这如果是不是个天大的“伪需求”&#xff0c;便是一场开发者的噩梦&#xff01; 要知道&#xff0c;如果没有上百亿的资金和数百名研发工程师的投入&#xff0c;从头开始构建一个新的浏览器引擎&#xff0c;几乎是不可能的。然而SerenityOS系统…