Webservice for system info: client part

By | 06/09/2014

Introduction

In this post, we created a webservice that would allow us to store system information such as public and private IP address or the system name of your computer. In this post, we will develop a small client to use the server.

GET /ip               Retrieves the list of all systeminfo from the database
GET /ip/:id           Retrieves a single systeminfo entry from the database
POST /ip              Inserts the systeminfo item in the database
DELETE /todos         Deletes the systeminfo item from the database

The client part

We would like to store our private and public IP address as well as our system name in the database. As this data is quite easily retrieved from the client side, we will use python to retrieve all info and have the client program call our REST API as described in this post.

The below snippet contains the core part of our client. It gathers the private and public IP address of our computer as well as the system name.

import socket
import json
import requests
from requests import get, post

def getPrivateIP():
    s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    s.connect(('8.8.8.8', 80))
    return s.getsockname()[0]

def getPublicIP():
	ip = get('http://api.ipify.org').text
	return ip

def getSystemName():
 	return socket.gethostname()

After we have retrieved the information on client side, we need to call the REST API from our python client using the REQUESTS library from Python:

url = 'http://publicprivateip.herokuapp.com/ip'

public 	= getPublicIP()
private = getPrivateIP()
systemname = getSystemName()

data = {"public": public, "private": private, "systemname": systemname}
headers = {'Content-type': 'application/json', 'Accept': 'text/plain'}

r = requests.post(url, data=json.dumps(data), headers=headers)

Executing the “python app.py” command will then store the information via REST in the database which is running on Heroku. Visit the herokuapp, in my case it’s on http://publicprivateip.com/ip, and you will see the entry added with your real private and public IP address as well as the name of your system.