通过指定的端口和协议找到服务名如果想找到网络服务,最好知道该服务运行在TCP或UDP协议的哪个端口上。如果知道网络服务使用的端口可以调用socket库中的getservbyport()函数来获取服务的名字。
技术点分解:
1、定义find_service_name()函数,注意函数内代码缩进
2、getservbyport(port,port_type),通过port查找service,port_type为‘tcp’和‘udp’两种
3、for-in 循环一组变量。在每次遍历中,获取端口对应的服务名
代码如下:
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这种常见的都显示报错,只当做测试使用吧,个人感觉没啥太大实用价值
运行结果:
本文出自 “老白的博客” 博客,请务必保留此出处http://laobaiv1.blog.51cto.com/2893832/1956451
原文地址:http://laobaiv1.blog.51cto.com/2893832/1956451