Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Free Learning
Arrow right icon
Arrow up icon
GO TO TOP
Python Network Programming Cookbook

You're reading from   Python Network Programming Cookbook Practical solutions to overcome real-world networking challenges

Arrow left icon
Product type Paperback
Published in Aug 2017
Publisher Packt
ISBN-13 9781786463999
Length 450 pages
Edition 2nd Edition
Languages
Tools
Concepts
Arrow right icon
Authors (3):
Arrow left icon
Dr. M. O. Faruque Sarker Dr. M. O. Faruque Sarker
Author Profile Icon Dr. M. O. Faruque Sarker
Dr. M. O. Faruque Sarker
Gary Berger Gary Berger
Author Profile Icon Gary Berger
Gary Berger
Pradeeban Kathiravelu Pradeeban Kathiravelu
Author Profile Icon Pradeeban Kathiravelu
Pradeeban Kathiravelu
Arrow right icon
View More author details
Toc

Table of Contents (15) Chapters Close

Preface 1. Sockets, IPv4, and Simple Client/Server Programming FREE CHAPTER 2. Multiplexing Socket I/O for Better Performance 3. IPv6, Unix Domain Sockets, and Network Interfaces 4. Programming with HTTP for the Internet 5. Email Protocols, FTP, and CGI Programming 6. Programming Across Machine Boundaries 7. Working with Web Services – XML-RPC, SOAP, and REST 8. Network Monitoring and Security 9. Network Modeling 10. Getting Started with SDN 11. Authentication, Authorization, and Accounting (AAA) 12. Open and Proprietary Networking Solutions 13. NFV and Orchestration – A Larger Ecosystem 14. Programming the Internet

Printing your machine's name and IPv4 address

Sometimes, you need to quickly discover some information about your machine, for example, the hostname, IP address, number of network interfaces, and so on. This is very easy to achieve using Python scripts.

Getting ready

You need to install Python on your machine before you start coding. Python comes preinstalled in most of the Linux distributions. For Microsoft Windows operating systems, you can download binaries from the Python website: http://www.python.org/download/.

Currently, Python 3.x is released in addition to Python 2.x. Many of the current Linux distributions and macOS versions are still shipping Python 2 by default. However, some ship both of them.

Download the relevant installer for your operating system and the relevant version based on whether your operating system is 32 bit or 64 bit.

You may consult the documentation of your operating system to check and review your Python setup. After installing Python on your machine, you can try opening the Python interpreter from the command line by typing python. This will show the interpreter prompt, >>>, which should be similar to the following output:

~$ python
Python 2.7.12 (default, Nov 19 2016, 06:48:10) 
[GCC 5.4.0 20160609] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> 
  

How to do it...

In the latter versions of Ubuntu since Ubuntu 14.04, Python 3 can be executed by typing python3:

~$ python3
Python 3.5.2 (default, Nov 17 2016, 17:05:23) 
[GCC 5.4.0 20160609] on linux
Type "help", "copyright", "credits" or 
"license" for more information.
>>>

Similarly, to be specific about which version you prefer to use, you may type python2 to execute Python 2 as well:

~$ python2
Python 2.7.12 (default, Nov 19 2016, 06:48:10) 
[GCC 5.4.0 20160609] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>>

There are a few changes in Python 3 that made some code written for Python 2 incompatible with Python 3. When you write network applications, try to follow the Python 3 best practices as these changes and improvements are back ported to the latter versions of Python 2. Thus, you may be fine by running the latest versions of Python 2 such as Python 2.7. However, some code developed focusing on Python 2 may not run on Python 3.

The following recipes in this chapter are written in Python 3. However, please keep in mind that a few network projects and modules may have been developed for Python 2. In that case, you will either have to port the application to Python 3 or use Python 2 depending on your requirements.

As this recipe is very short, you can try this in the Python interpreter interactively.

First, we need to import the Python socket library with the following command:

>>> import socket  

Then, we call the gethostname() method from the socket library and store the result in a variable as follows:

>>> host_name = socket.gethostname()
>>> print "Host name: %s" %host_name
Host name: llovizna
>>> print "IP address: %s" 
%socket.gethostbyname(host_name)
IP address: 127.0.1.1

The entire activity can be wrapped in a free-standing function, print_machine_info(), which uses the built-in socket class methods.

We call our function from the usual Python __main__ block. During runtime, Python assigns values to some internal variables such as __name__. In this case, __name__ refers to the name of the calling process. When running this script from the command line, as shown in the following command, the name will be __main__. But it will be different if the module is imported from another script. This means that, when the module is called from the command line, it will automatically run our print_machine_info function; however, when imported separately, the user will need to explicitly call the function.

Listing 1.1 shows how to get our machine info, as follows:

#!/usr/bin/env python
# Python Network Programming Cookbook,
Second Edition -- Chapter - 1 # This program is optimized for Python 2.7.12
and Python 3.5.2. # It may run on any other version with/without
modifications. import socket def print_machine_info(): host_name = socket.gethostname() ip_address = socket.gethostbyname(host_name) print ("Host name: %s" %host_name) print ("IP address: %s" %ip_address) if __name__ == '__main__': print_machine_info()

In order to run this recipe, you can use the provided source file from the command line as follows:

$ python 1_1_local_machine_info.py  

On my machine, the following output is shown:

Host name: llovizna
IP address: 127.0.1.1
  

The hostname is what you assigned to your computer when you configured your operating system. This output will be different on your machine depending on the system's host configuration. Here hostname indicates where the Python interpreter is currently executing.

Please note that the programs in this book are run with both versions 2 and 3. We avoid mentioning python3 and python2 in commands, as they are too specific to some distributions and assumes that a specific version is installed. You may run any of the programs in either version by using python2 or python3 accordingly.

How it works...

The import socket statement imports one of Python's core networking libraries. Then, we use the two utility functions, gethostname() and gethostbyname(host_name). You can type help(socket.gethostname) to see the online help information from within the command line. Alternatively, you can type the following address in your web browser at http://docs.python.org/3/library/socket.html. You can refer to the following code:

    gethostname(...)
        gethostname() -> string 
        Return the current host name. 
    
    gethostbyname(...) 
        gethostbyname(host) -> address 
        Return the IP address (a string of the form 
'255.255.255.255') for a host.

The first function takes no parameter and returns the current or localhost name. The second function takes a single hostname parameter and returns its IP address.

You have been reading a chapter from
Python Network Programming Cookbook - Second Edition
Published in: Aug 2017
Publisher: Packt
ISBN-13: 9781786463999
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $19.99/month. Cancel anytime
Banner background image