External IP Scrapper in Java

Introduction: This tutorial is on how to create a simple tool in Java to display your external IP. Note: We are going to be using the site http://checkip.amazonaws.com/ to return our IP. As this is a website, it may change in the future, you can check if this still works by simply going to it in your browser and comparing if to another ip checker such as http://www.cmyip.com. Imports: First we need to import quite a few modules...
  1. import java.io.BufferedReader;
  2. import java.io.IOException;
  3. import java.io.InputStreamReader;
  4. import java.net.URL;
  5. import java.net.URLConnection;
IOException is to catch any IOExceptions that occur. BufferedReader is to read the web page string as a response. InputStreamReader is to read the response to a string for the web page. URL and URLConnection are to access the web page. Main Method: Now we are going to create the main method so we have something run once the application is started...
  1. public class Main {
  2.         public static void main(String[] args) throws IOException
  3.     {
  4.     }
  5. }
URL: Now we want to create the connection to the web page. This 'con' will be used to access the page...
  1. public class Main {
  2.         public static void main(String[] args) throws IOException
  3.     {
  4.                 URL connection = new URL("http://checkip.amazonaws.com/");
  5.         URLConnection con = connection.openConnection();
  6.     }
  7. }
Finally: Finally we just read the web page connection through InputStreamReader and BufferedReader to a string 'str' from our BufferedReader 'reader' and then output the string. Notice how we use 'reader.readline()', that is because on the website itself, the ip is only on one line which makes it easier for us to extract it and therefore is why we are using it for this tutorial as opposed to another site which breaks up the ip split by a fullstop ('.')...
  1. public class Main {
  2.         public static void main(String[] args) throws IOException
  3.     {
  4.                 URL connection = new URL("http://checkip.amazonaws.com/");
  5.         URLConnection con = connection.openConnection();
  6.         String str = null;
  7.         BufferedReader reader = new BufferedReader(new InputStreamReader(con.getInputStream()));
  8.         str = reader.readLine();
  9.         System.out.println(str);
  10.     }
  11. }

Add new comment