Internet Address IP

With Java you can use the java.net package to find out details of your PC address or somewhere else (like www.google.com) with using the InetAddress class. The InetAddress is a implementation of the Internet Protocol basically.

To gain the local pc address you can use

InetAddress theHost = InetAddress.getLocalHost();
System.out.println("Local host address: "+theHost);

which would get the local PC address and display it to the screen, for me it would something like

Local host address: genux-laptop/127.0.1.1

you can get the individual parts of the above address, e.g. genux-laptop and 127.0.0.1

System.out.println("Local host name : " +theHost.getHostName());
System.out.println("Local address : "+theHost.getHostAddress());

and the output would be

Local host name :  genux-laptop
Local address : 127.0.1.1

you can also use the InetAddress to obtain remote addresses for example www.google.com so to pull details back from google you could use the getByName function that is within the InetAddress class as.

System.out.println("Host address of google.com : "+ InetAddress.getByName("www.google.com"));

Here is a full code that does the above in full

import java.io.*;
import java.net.*;
 
public class address {
		public static void main(String[] args)
		{
			// a inetaddress class holds details of internet protocol (IP) address
 
			InetAddress theHost = null;
			// you can get the local host (your PC) addresss
			try {
				theHost = InetAddress.getLocalHost();
				System.out.println("Local host address: "+theHost);
			}
			catch (UnknownHostException unknow)
			{
				System.out.println("Error : "+ unknow.toString());
				return;
			}
			// if there is no local host then, oppss!!.. you should really have a local host name
			// also you get can the local host name and address individual 
			String theHostName = theHost.getHostName();
			String theHostAddress = theHost.getHostAddress();
 
			System.out.println("The host name "+ theHostName);
			System.out.println("The host address " + theHostAddress);
 
			try {
				// you can a reverse look up as such by passing in the local name to get the IP address
				System.out.println("Host address by host name : "+ InetAddress.getByName(theHostName));
 
				// if you wanted to get a google host name then just pass in www.google.com
				System.out.println("Host address of google.com : "+ InetAddress.getByName("www.google.com"));
			}
			catch (UnknownHostException unknow)
			{
				System.out.println("Error : "+ unknow.toString());
			}
		}
}

and the output would be

Local host address: genux-laptop/127.0.1.1
The host name genux-laptop
The host address 127.0.1.1
Host address by host name : genux-laptop/127.0.1.1
Host address of google.com : www.google.com/216.239.59.105

Leave a Reply

Your email address will not be published.