socket.getaddrinfo(host, port, family=0, type=0, proto=0, flags=0)
- If we know a network service by host name like example.org or the IP address of the network service either in form of IPv4 or IPv6 along with the port number of the network service, getaddrinfo() will return a list of tuples containing information about socket(s) that can be created with the service.
For example, by specifying example.org, 80 as values for the hostname and port number parameters getaddrinfo() queries what kind of client sockets need to be created to connect to example.org.
- Remember, all the socket tuples returned may not be fully supported.
For instance, querying to example.org provides one of the tuples containing information required for creating datagram socket to it - <SocketKind.SOCK_DGRAM: 2>.
However, we do not know any web server is fully supporting HTTP over UDP. The returned value could be on a future note and in accordance to the specifications rather than practically support the whole HTTP on UDP.
- Examining other tuples returned in the example below reveals that there are tuples with <SocketKind.SOCK_STREAM: 1>.
It means TCP sockets can be created to connect to the service at example.org.
- Also the tuples returned convey that both IPv4(AddressFamily.AF_INET: 2) and IPv6(AddressFamily.AF_INET6 ) address families are supported.
host: The host parameter takes either an ip address or a host name.
The ip address can be either an ipv4 address or an ipv6 address.
When a host name is used the Domain Name Service(DNS)
will be used for resolving the name into an IP address.
port: The port number of the service. If zero information is returned for
all supported socket types.
proto, flags - These parameters act like a filter so that the
getaddrinfo()returns the tuples pertaining only to the
types specifiedin them. For example if family=AF_INET only
the tuples corresponding to sockets supporting IPv4 address
family will be returned provided they are supported by the
# Query for socket information to connect to example.com
addrInfo = socket.getaddrinfo("example.com",80)
# print socket tuples
[(<AddressFamily.AF_INET: 2>, <SocketKind.SOCK_DGRAM: 2>, 17, '', ('18.104.22.168', 80)),
(<AddressFamily.AF_INET: 2>, <SocketKind.SOCK_STREAM: 1>, 6, '', ('22.214.171.124', 80)),
(<AddressFamily.AF_INET6: 30>, <SocketKind.SOCK_DGRAM: 2>, 17, '', ('2606:2800:220:1:248:1893:25c8:1946', 80, 0, 0)),
(<AddressFamily.AF_INET6: 30>, <SocketKind.SOCK_STREAM: 1>, 6, '', ('2606:2800:220:1:248:1893:25c8:1946', 80, 0, 0))]
The output above lists all the tuples as returned by getaddrinfo().
The tuples convey that the service example.org at port number 80 supports both Datagram Sockets (UDP) as well as connection oriented sockets (TCP).
They also reveal that the sockets can be created either using AF_INET or AF_INET6 address families.