且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

python通过端口和协议查出服务名

更新时间:2022-09-21 23:38:56

    通过指定的端口和协议找到服务名如果想找到网络服务,***知道该服务运行在TCP或UDP协议的哪个端口上。如果知道网络服务使用的端口可以调用socket库中的getservbyport()函数来获取服务的名字。


技术点分解:

1、定义find_service_name()函数,注意函数内代码缩进

2、getservbyport(port,port_type),通过port查找service,port_type为‘tcp’和‘udp’两种

3、for-in 循环一组变量。在每次遍历中,获取端口对应的服务名


代码如下:

1
2
3
4
5
6
7
8
import  socket
def find_service_name():
    port_type = 'tcp'
    port_type1 = 'udp'
    for port in [25,80,22]:
        print ("Port: %s => service name: %s" %(port,socket.getservbyport(port,port_type)))
    print("Port: %s => service name: %s" % (53, socket.getservbyport(53, 'udp')))
find_service_name()

备注:socket.getservbyport这函数定义的端口种类过少,经过测试像3306 mysql这种常见的都显示报错,只当做测试使用吧,个人感觉没啥太大实用价值

运行结果:

python通过端口和协议查出服务名


本文转自 yuri_cto 51CTO博客,原文链接:http://blog.51cto.com/laobaiv1/1956451,如需转载请自行联系原作者