Subscribe to geohhot's Blog        RSS Feed

Getting location using IP in java

Icon Leave Comment
I used this function in my IRC bot, for getting location and than getting weather with that. So I think about making something like tutorial about it.
First step: getting app key
At first what we going to do: get app key in ipInfoDB. For that just follow this link and register here. After that you will get and e-mail and you will activate your account. In the end you will get app-id which we will use after.
So write that key to a String named key, like:
public Static String key = "<your_key_here>";

Second step: writing function to get info
Now import 2 libraries that we will need:

For this will start coding. We will write new function called getInfo which will return string, and have string containing IP as an argument.
So ..
public static String getInfo(String ip) throws IOException {
	String url = ""
		+ key + "&ip=" + ip;
	URL ipInfoDB = new URL(url);
	HttpURLConnection conn = (HttpURLConnection) ipInfoDB.openConnection();
	if(conn.getResponseCode() != 200) {
		System.out.println("Network error: "+conn.getResponseMessage());
		return "Error";
	BufferedReader rd = new BufferedReader(
			  new InputStreamReader(conn.getInputStream()));
	StringBuilder sb = new StringBuilder();
	String line;
	while ((line = rd.readLine()) != null) {
	// at this point we have response
	String response = sb.toString();
	return response;

Great now we have response something like this:

and we need to parse that.
Third step: Parsing data
For parsing data, we will write another function which will return location. If we will look at the String that we got on response, will see that it is something like matrix of strings, and the 3rd, 4th, 5th and 6th strings are the location that we need, so function will just split response to an array and then function will return that four string joined with spaces.
public static String parseInfo(String response) {
	String params[] = response.split(";");
	return params[3]+" "+params[4]+" "+params[5]+" "+params[6];

And that is all we need, main function will look like this:
public static void main(String[] args) {
	try {
		String response = getInfo("");
		String location = parseInfo(response);
		System.out.println("Location is: "+location);
	} catch(IOException e) {

This is all, you can download file ( Attached File  gettingLocationFromIp.txt (1.3K)
Number of downloads: 72 )
In case of questions and/or problems please email me.
Follow me@ghindoyan

0 Comments On This Entry


Trackbacks for this entry [ Trackback URL ]

There are no Trackbacks for this entry

June 2016

262728 29 30   

Recent Entries

Search My Blog

0 user(s) viewing

0 Guests
0 member(s)
0 anonymous member(s)