Python and Networks

Challenge 6-1: Network Programming

There are certain functions we can use in Python to find the IP address of certain servers. Let’s take an imaginary website, www.example.org , to see the steps…

>>> import socket

Here we have used the import function in Python. This is used to gain access to the code in another Python module. A Python module is a file containing Python code, statements, and so on. Often the module file contains the extension “.py” at the end so it is easy to identify.

In this case, the module we have imported is called socket. This is a built-in Python module that contains functions that allow you to access the internet.

>>> import socket

>>> hostname = "www.example.org"

You will see here we have defined a variable called hostname. A network host is simply a device or server connected to the network.

In this case, our host is the example.org server. You may also notice the web address is written with quote marks around it – refer back to Challenge 1-3: Strings to remind yourself why!

>>> import socket

>>> hostname = “www.example.org”

>>> IPAddress = socket.gethostbyname(hostname)

Now we have added the gethostbyname function in Python. This function will return (i.e., output) the IP address of the host we have defined in the previous step – the example.org server.

>>> import socket

>>> hostname = “www.example.org”

>>> IPAddress = socket.gethostbyname(hostname)

>>> print("IP Address of the host name {} is: {}".format(hostname, IPAddress))

Here, we have added the Python print function. We've used this before in a number of challenges, but this time we're using some extra magic - the .format() method. Notice the different types of brackets we have used.

The curly brackets {} create a placeholder for the requested information that will appear in the output. You will see there are two sets of these.

This is where the Python string.format() function comes in. By writing .format(hostname, IPAddress) at the end of the string, we are specifying that in place of the first set of curly brackets we want the hostname, and in place of the second set of curly brackets we want to see the IPAddress.

Therefore, this code would return:

>>> IP Address of the host name www.example.org is 91.234.256.43