Finding service name for the given port numer

This blog finds service name for the port number entered by user.

Sometimes there is a need to find service name for the port.
Use getservbyport() function to find service name of the port
This function is from the socket module.

Syntax
socket.getservbyport(port)

Code : Finding service name for the entered port number

Import socket module to utilize getservbyport() function

import socket

Use getservbyport() function to find service name for the port number

try:
    port = int(input('Enter a port: '))
    print(socket.getservbyport(port))
except:
    print('Enter correct port number')

We have use try and except incase user enters some alphanumeric character, program will display message “Enter correct port number”

Output(Successful)

Enter a port: 23
telnet

Output(User entered alphanumeric characters)

Enter a port: 56wf
Enter correct port number

Complete Code

import socket
try:
    port = int(input('Enter a port: '))
    print(socket.getservbyport(port))
except:
    print('Enter correct port number')
Advertisement

Leave a Comment

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s