GetnameInfo() In Python

Overview:

  • Given a socket address consisting of an IP address and a Port Number as a tuple, GetnameInfo() returns the text values for both of them.
  • GetnameInfo() method does a DNS lookup to fetch the text representation corresponding to the IP and Port/Service.
  • When the lookup fails to get the text representation, numeric representation is returned if the value of flag is not NI_NAMEREQD. If the value of the flag is NI_NAMEREQD, then an error is raised.
  • When NI_NOFQDN is specified as the value for the flag, only the host name portion of the text is returned. However, the port number will be translated to the service name. For example, port number 443 for example.com returns the string 'https'.
  • When NI_NUMERICHOST is specified as the value for the flag, only the port number is translated to text. The FQDN(Fully Qualified Domain name) is returned as numeric only.
  • When the NI_NUMERICSERV is specified as the flag, FQDN will be translated to text if text is available. The service part is returned as numeric itself.

Example:

# ----- Example Program for getnameinfo() method of Python's socket module -----

 

import socket

 

# Get only host name part of the Fully Qualified Domain Name,

# Port number will be translated to service name

sockAddr = ("93.184.216.34", 443);

sockInfo = socket.getnameinfo(sockAddr, socket.NI_NOFQDN);

print(sockInfo);

 

# Get numeric representation of the host, port number translated to service name

sockAddr = ("93.184.216.34", 443);

sockInfo = socket.getnameinfo(sockAddr, socket.NI_NUMERICHOST);

print(sockInfo);

 

# Get FQDN as text and port number as numeric

sockAddr = ("93.184.216.34", 443);

sockInfo = socket.getnameinfo(sockAddr, socket.NI_NUMERICSERV);

print(sockInfo);

 

# If numeric to text lookup of the host fails, raise an error

sockAddr = ("93.184.216.34", 80);

sockInfo = socket.getnameinfo(sockAddr, socket.NI_NAMEREQD);

print(sockInfo);

 

Output:

('93.184.216.34', 'https')

('93.184.216.34', 'https')

('93.184.216.34', '443')

Traceback (most recent call last):

  File "getnameinfo.py", line 23, in <module>

    sockInfo = socket.getnameinfo(sockAddr, socket.NI_NAMEREQD);

socket.gaierror: [Errno 8] nodename nor servname provided, or not known

 

 


Copyright 2023 © pythontic.com