In this tutorial you will learn about the Java Program to Get IP Address and its application with practical example.
Java Program to Get IP Address
In this tutorial, we will learn to create a Java program that will get the IP address of the computer using Java programming.
Prerequisites
Before starting with this tutorial, we assume that you are the best aware of the following Java programming topics:
- Operators in Java Programming.
- Basic Input and Output function in Java Programming.
- Basic Java programming.
- Header Libraries and their usage.
Get IP address
In Java programming, it is possible to take or fetch the ip address from the computer and convert it into words or can display in words with the help of a very small amount of code. The Java language has many types of header libraries which has supported function in them, with the help of these files the programming is easy.
Algorithm:-
1 2 3 4 5 6 7 8 9 |
1. Create a socket to define network interface IPv4. 2. Define the IPv4 address type. 3. Define the port name where network is attached. 4. Access the network interface information by passing address using ioctl. 5. Extract the IP address. |
Program:-
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
import java.net.InetAddress; //Importing java packages. public class GetIpAddress //Main Class function { //Body of the main function public static void main(String args[]) throws Exception{ //Fetching the ip address of the machine InetAddress addr = InetAddress.getLocalHost(); //Printing the host machine ip address to the user System.out.println("Local HostAddress: "+addr.getHostAddress()); String hostname = addr.getHostName(); //Printing the host machine name to the user System.out.println("Local host name: "+hostname); } } |
Output:-
In the above program, we have first initialized the required variable.
- addr = it will hold the ip address of the machine on the network.
- hostname = it will hold the host name of the machine on the network.
Including the packages files required for the program.
First we will retrieving the ip address of the machine on the network.
Body of the Main function of the program.
Printing the ip address of the machine.
Printing the host name of the machine.