/* * Compile with: * valac --pkg=glib-2.0 --pkg=libsoup-2.4 --pkg=json-glib-1.0 geoip.vala * * Get country code from IP address. * */ public class GeoIP : Object { private const string HOSTNAME = "www.telize.com"; private string address; private Soup.URI uri; #if LIBSOUP_2_42 private Soup.Session session; #else private Soup.SessionSync session; #endif private Soup.Message msg; public GeoIP () { /* Create Soup.URI object */ address = "http://%s".printf (HOSTNAME); this.uri = new Soup.URI (address); /* Create session object */ #if LIBSOUP_2_42 this.session = new Soup.Session (); #else this.session = new Soup.SessionSync (); #endif } public void run (string resource) { string content = null; content = send_query (resource); if (content != null) { parse_json (content); } } private void parse_json (string data) { Json.Parser parser; Json.Node node; unowned Json.Object obj; parser = new Json.Parser (); try { parser.load_from_data (data); } catch (GLib.Error e) { stderr.printf ("Error: '%s'\n", e.message); } node = parser.get_root (); if (node.get_node_type () == Json.NodeType.OBJECT) { obj = node.get_object (); foreach (unowned string name in obj.get_members ()) { if (name == "country_code") { unowned string item; item = obj.get_string_member (name); stdout.printf ("%s\n", item.down ()); } } } } private string send_query (string resource) { string content = null; this.uri.set_path ("/%s".printf (resource)); msg = new Soup.Message.from_uri ("GET", this.uri); this.session.send_message (msg); #if VALA_0_22 if (Soup.Status.OK == msg.status_code) { #else if (Soup.KnownStatusCode.OK == msg.status_code) { #endif content = (string) msg.response_body.flatten ().data; } return content; } } void main (string[] argv) { string path = "geoip"; GeoIP ip; ip = new GeoIP (); ip.run (path); }