Program to find service name for multiple port numbers

In this program, we will ask user to enter port number and display its service name. Program will get terminate when the user enter ‘q’

Importing socket module

import socket

Display description of the program

print('Program to find service name')

Creating a variable called con and assigning empty value

con = ''

Using while loop to check whether the value of con is equal to ‘q’. In the first loop, the value is empty so the statement is true and while loop will execute

while con != 'q':

Now we will ask to enter a port number. Program will display service name if the port number is valid. For any invalid entry, program will display message ‘Service name not found’

Program is accepting value in a string format. Before we use getservbyport() function to find port number, entered value need to be converted into integer.

if the user enter ‘q’, program will get terminate

while con != 'q':
try:
con = input('Enter a port: ')
if con == 'q':
print('Program quit')
else:
port = int(con)
print(socket.getservbyport(port))
except:
print('Service name not found')

Output

Program to find service name
Enter a port: sd
Service name not found
Enter a port: 80
http
Enter a port: 43
nicname
Enter a port: 445
microsoft-ds
Enter a port: 53
domain
Enter a port: 1024
Service name not found
Enter a port: 12
Service name not found
Enter a port: 21
ftp
Enter a port: 23
telnet
Enter a port: 22
ssh
Enter a port: q
Program quit

Complete Code

import socket
print('Program to find service name')
con = ''
while con != 'q':
try:
con = input('Enter a port: ')
if con == 'q':
print('Program quit')
else:
port = int(con)
print(socket.getservbyport(port))
except:
print('Service name not found')

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