In this blog, we will be writing a program that identify service name for port number and save the result into text file. Later we can open the text file to check the result
First of all import socket module in the program
import socket
Then creating a file handler with open() function. Open() function takes file name and file mode. Below open() function takes complete path to file and the filename. File will be open in write mode.
f = open('C:/Users/rohit/Desktop/Rohan/Files/Test.txt','w')
Creating a variable con with null value
con = ''
Writing heading into the file using f.write()
f.write('Ports and their service names\n')
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
try:
con = input('Enter a port: ')
if con == 'q':
print('Program quit')
else:
port = int(con)
service_name = socket.getservbyport(port)
print(socket.getservbyport(port))
f.write('\n')
f.write(con)
f.write(service_name)
except:
print('Service name not found')
Output
Enter a port: 53
domain
Enter a port: 443
https
Enter a port: sd
Service name not found
Enter a port: 80
http
Enter a port: 445
microsoft-ds
Enter a port: 11
systat
Enter a port: 101
hostname
Enter a port: 25
smtp
Enter a port: 169
Service name not found
Enter a port: q
Program quit
Process finished with exit code 0
Now opening the text file where all output was diverted.

Complete Code
import socket
f = open('C:/Users/rohit/Desktop/Rohan/Files/Test.txt','w')
con = ''
f.write('Ports and their service names\n')
while con != 'q':
try:
con = input('Enter a port: ')
if con == 'q':
print('Program quit')
else:
port = int(con)
service_name = socket.getservbyport(port)
print(socket.getservbyport(port))
f.write('\n')
f.write(con)
f.write(service_name)
except:
print('Service name not found')
f.close()
Remember to close the file. Otherwise this will occupy memory