Python网络编程——通过指定的端口和协议找到服务名

1.通过指定的端口和协议找到对应的服务名,采用socket中getservbyprot()函数实现。

 1 import socket
 2 
 3 
 4 def find_service_name():
 5     protocolname = 'tcp'
 6     for port in [80, 25]:
 7         print("Port: %s => service name: %s" % (port, socket.getservbyport(port, protocolname)))
 8 
 9     print("Port: %s => service name: %s" % (53, socket.getservbyport(53, 'udp')))
10 
11 if __name__ == '__main__':
12     find_service_name()

2.输出结果

1 Port: 80 => service name: http
2 Port: 25 => service name: smtp
3 Port: 53 => service name: domain

3.socket.getservbyport()解释

 1 def getservbyport(port, protocolname=None): # real signature unknown; restored from __doc__
 2     """
 3     getservbyport(port[, protocolname]) -> string
 4 
 5     Return the service name from a port number and protocol name.
 6     The optional protocol name, if given, should be 'tcp' or 'udp',
 7     otherwise any protocol will match.
 8     """
 9     return
10 # 获取对应端口的服务名
原文地址:https://www.cnblogs.com/ouyangyixuan/p/5871946.html