DNS lookup

You can use the getaddrinfo() function in the socket module to perform a DNS lookup of a of a domain name, or retrieve information about a domain name or IP address.

In this example, this code imports the socket module and uses getaddrinfo() to perform a DNS lookup on www.micropython.org. The target port is 80.

For detailed information about getaddrinfo(), see micropython.org/resources/docs/en/latest/wipy/library/usocket.html.

  1. Access the MicroPython environment.
  2. Copy the sample code shown below.
  3. Press Crtl+E to enter paste mode.
  4. At the MicroPython >>> prompt, right-click and select the Paste option.
import socket 
# Return tuple (family, type, proto, canonname, sockaddr) 
print("\nCalling getaddrinfo() for micropython.org on port 80,")
print("this will return information about the host address in the")
print("following format:")
print("[family, type, proto, canonname, sockaddr]\n")
print(socket.getaddrinfo('www.micropython.org', 80))  
 
# Return sockaddr, which consists of an IP address and port
print("\nCalling getaddrinfo(), but returning only the address/port tuple")
print("(\"sockaddr\") via indexing the output of getaddrinfo().\n")
print(socket.getaddrinfo('www.micropython.org', 80)[0][-1])
 
# Return the IP address only
print("\nFinally, returning ONLY the IP address, via more specific")
print("indexing.\n")
print(socket.getaddrinfo('www.micropython.org', 80)[0][-1][0])
  1. Once pasted, the code should execute immediately. The output should be similar to the output shown below.
Calling getaddrinfo() for micropython.org on port 80, this will
 
return information about the host address in the following format:
[family, type, proto, canonname, sockaddr]
 
[(2, 1, 0, '', ('176.58.119.26', 80))]
 
Calling getaddrinfo(), but returning only the address/port tuple
("sockaddr") via indexing the output of getaddrinfo().
 
('176.58.119.26', 80)
 
Finally, returning ONLY the IP address, via more specific
indexing.
 
176.58.119.26