OSError: port/proto not found in for loop

Question:

I wrote a python script using the socket module, which provides getservbyport for retrieving a service name based on a port number argument.

I used the following code:

import socket
socket.getservbyport(443) # 'https'

But with certain port numbers i’m getting the following error:

socket.getservbyport(675)
Traceback (most recent call last):
  File "<pyshell#1>", line 1, in <module>
    socket.getservbyport(675)
OSError: port/proto not found

Can someone explain to me why i am getting this error?

Also i want to list the services with their matching port, so I eliminated the errors using try and except method like the following code:

for i in range(0,65536,1):
    try:
        print(i,"Runs, service:",socket.getservbyport(i))
    except:
        continue

I’m getting the ports which have a service, but I want to list the serial numbers before the port numbers. Since I used except method the errors are eliminated so I can’t number them.

Asked By: Sundararajan

||

Answers:

The error OSError: port/proto not found is thrown when no service is found on that port. So if you’re iterating through all possible ports, odds are you will almost certainly get that error. Catching the error is the right way to go.

To achieve what you need, use a separate counter to keep track of the number of services found:

counter = 1
for i in range(0, 65536):
    try:
        service = socket.getservbyport(i)
        print(counter, " port nr ", i, " runs service ", service)
        counter += 1
    except:
        continue

Alternatively if you would like the services data elsewhere, store the services in-order in an array, like so:

services = []
for i in range(0, 65536):
    service = None
    try:
        service = socket.getservbyport(i)
    except:
        pass
    if service is not None:
        services += [{'service': service, 'port': i}]

for idx, s in enumerate(services):
    print(idx, " port nr ", s['port'], " runs service ", s['service'])
Answered By: Elwin Arens

You can solve the problem of
OSError: port/proto not found
by adding the tcp protocol like this

import socket
print(socket.getservbyport(22, "tcp"))
Answered By: حمزة