Resolving the IP address with the socket package

If you would like to see the local machine IP, you can do so using the ifconfig command in Linux and the ipconfig command in Windows. Here, we'll do this in Python using the built-in function:

>>> import socket
>>> socket.gethostbyname('python.org')
'10.0.2.15'

This process is known as a host file-based name resolution. You can send a query to a DNS server and ask for the IP address of a specific host. If the name has been registered properly, you will get a response from the server.

Here are some useful methods for gathering this kind of information:

  • socket.gethostbyaddr(address): This allows us to obtain a domain name from the IP address.
  • socket.gethostbyname(hostname): This method converts a hostname into IPv4 address format. The IPv4 address is returned in the form of a string. This method is equivalent to the nslookup command that we can find in many operating systems.
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset