Make a Ping Network Utility tool using Django

You must have used ping command on your Command Prompt or Terminal to check if a site is up or to get it’s IP Address.

Ping is a network utility command used to check if a host is reachable. It is there is almost every operating system.

Let’s see how we can make a Django App for the same.

Ping Utility tool

Overview of the Application

The user inputs the domain name. After submitting the domain is entered on the server with the ping command. The server response is send back to the application.

Now, lets see all code needed for this application.

urls.py

url /ping is mapped to view ping.

urlpatterns = [
      url(r'^ping/$', views.ping),
]

ping.html

When submit button is clicked the url is sent to the View function mapped to the url.

ping_output will contain the ping command output from the view function.

<div class="network-tool" id="ping">
	<h1>Ping</h1>

	<form action="/ping" method="get">
	    <label for="">Enter Domain: eg: example.com</label>
	    <input name="q">
	  <button type="submit">Submit</button>
	</form> 
	<div class="tool-output">{{ping_output|linebreaks}}</div>
</div>

views.py

The ping command is executed using the os.popen() command. The c option is used here to limit to only 4 packets. popen() it takes argument as string.

popen returns an object so it must be converted into string using read() method.

The request is stored as key-value pair. the value as the domain name and q as the key from our form.

ping command output is stored in the context and finally rendered on the html page.

def ping(request):

	context = {}

	if request.GET.get('q', False) == '':
		context['ping_output'] = 'Please enter a domain name!'
	
	elif 'q' in request.GET:
		ping_output = os.popen('ping -c 4 ' + request.GET['q']).read()
		context['ping_output'] = ping_output
	
	return render(request,'ping.html',context)

Leave a Reply

Your email address will not be published. Required fields are marked *