getservbyname() function in Python

The getservbyname() function in Python takes a service name and the protocol name and returns the defined port of the service.

socket Updated 7 Feb 2017 1 min read

Function Name

getservbyname

Function Signature

getservbyname(servicename, protocolname)

Function overview

The function getservbyname() takes a network service name and an underlying protocol name and returns the port number on which the service is defined by /etc/services. By network service we mean an application protocol like http or ftp. The underlying protocol means is the transport layer protocol like tcp or udp.

Exceptions

OSError is raised if the service name or the protocol name mentioned is not defined in the system. Note that, the servicename and protocolname are both case sensitive. If HTTP is passed for servicename instead of http,

the function will raise an OSError stating "service/proto not found".

Parameters

servicename - The network service name ie., application protocol

protocolname - Name of the underlying transport layer protocol either tcp

or udp. This is an optional parameter.

If this is not provided any protocol will be matched.

As per IANA, it is the policy to define a well known and same

port number for both tcp and udp protocols of a service.

Example

python
import socket

#Service list has a list of application protocols

serviceList = [

              "daytime",

              "ftp",

              "gopher",

              "http",

              "https",

              "imap",

              "kerberos-adm",

              "mysql-im",

              "pop3",

              "qotd",   #quote of the day

              "ssh",    #ssh remote login protocol

              "snmp",

              "smtp"]

underlyingProtocol = "tcp"

print("======>Services and their port numbers<======")

for service in serviceList:

    #get the port number for each application protocol which uses TCP as underlying

    portNum = socket.getservbyname(service, underlyingProtocol)

    print("The service {} uses port number {} ".format(service, portNum))

Output

Output
The service daytime uses port number 13

The service ftp uses port number 21

The service gopher uses port number 70

The service http uses port number 80

The service https uses port number 443

The service imap uses port number 143

The service kerberos-adm uses port number 749

The service mysql-im uses port number 2273

The service pop3 uses port number 110

The service qotd uses port number 17

The service ssh uses port number 22

The service snmp uses port number 161

The service smtp uses port number 25