Getservbyport() - Get Service Name From Port Number Using Python

Overview:

The getservbyport()function from Python’s socket module returns the name of the service for a given port number. Along with port number, the protocol name – “tcp” or “udp” needs to be specified as the value for the second parameter to getservbyport().

Example:

The example Python program retrieves service names for the port numbers 21, 105, 80 and 443.

As per the output for port number 21 the string “ftp” is returned denoting File Transfer Protocol. For port number 105, value “sco“ is returned. For port number 80, the string “http” is returned which stands for Hyper Text Transfer Protocol, which is the backbone of the World Wide Web. For port number 443, the value “https” is returned which denotes Hyper Text Transfer Protocol.

# Example program for getting service names from port number using getservbyport()of Python's scoket module

import socket

 

def printServiceOnPort(portNumber, protocol):

    serviceName = socket.getservbyport(portNumber, protocol);

    print("Name of the service running at port number %d : %s"%(portNumber, serviceName));

   

printServiceOnPort(21,  "tcp");

printServiceOnPort(105, "tcp");

printServiceOnPort(80,  "tcp");

printServiceOnPort(443, "tcp");

 

Output:

Name of the service running at port number 21 : ftp

Name of the service running at port number 105 : cso

Name of the service running at port number 80 : http

Name of the service running at port number 443 : https


Copyright 2019 © pythontic.com