Home » Core Java » net » InetAddress » How to get IP address in Java using InetAddress

About Ilias Tsagklis

Ilias Tsagklis
Ilias is a software developer turned online entrepreneur. He is co-founder and Executive Editor at Java Code Geeks.

How to get IP address in Java using InetAddress

An Internet Protocol address (IP address) is a numerical label assigned to each device (e.g., computer, printer) participating in a computer network that uses the Internet Protocol for communication. The designers of the Internet Protocol defined an IPv4 address as a 32-bit number.

In this tutorial we are going to see how can you get the IP Address that is assigned to your own machine inside your local network and the IP Addresses assigned to specific Domain Names(e.g. www.google.com…).

To do that we are going to use InetAddress.To be more specific we are going to use:

  • getLocalHost().getHostAddress() method of InetAddress to get the IP Address of our machine in our local network
  • getByName() method of InetAddress to get the IP Address of a specific Domain Name
  • getAllByName() method of InetAddress to get all the IP Address of a specific Domain Name.

So, let’s see the code:

package com.javacodegeeks.java.core;

import java.net.InetAddress;
import java.net.UnknownHostException;

public class GetIpAddress {

	public static void main(String[] args) throws UnknownHostException {

		// print the IP Address of your machine (inside your local network)
		System.out.println(InetAddress.getLocalHost().getHostAddress());

		// print the IP Address of a web site
		System.out.println(InetAddress.getByName("www.javacodegeeks.com"));

		// print all the IP Addresses that are assigned to a certain domain
		InetAddress[] inetAddresses = InetAddress.getAllByName("www.google.com");

		for (InetAddress ipAddress : inetAddresses) {
			System.out.println(ipAddress);
		}
	}
}

Output:

192.168.1.100
www.javacodegeeks.com/64.64.30.146
www.google.com/173.194.39.244
www.google.com/173.194.39.242
www.google.com/173.194.39.241
www.google.com/173.194.39.240
www.google.com/173.194.39.243

 
This was an example of how to get IP address in Java using InetAddress.

(No Ratings Yet)
1 Comment Views Tweet it!

Do you want to know how to develop your skillset to become a Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you our best selling eBooks for FREE!

 

1. JPA Mini Book

2. JVM Troubleshooting Guide

3. JUnit Tutorial for Unit Testing

4. Java Annotations Tutorial

5. Java Interview Questions

6. Spring Interview Questions

7. Android UI Design

 

and many more ....

 

Receive Java & Developer job alerts in your Area

 

1
Leave a Reply

avatar
1 Comment threads
0 Thread replies
0 Followers
 
Most reacted comment
Hottest comment thread
1 Comment authors
sykrh Recent comment authors
  Subscribe  
newest oldest most voted
Notify of
sykrh
Guest
sykrh

how to checks this in CMD?