Get Local IP Address and Hostname In Java

Get Local IP Address and Hostname In Java

Below Example determine Local IP Address and Hostname of local computer using Java API.

java.net.InetAddress – class represents an Internet Protocol (IP) address.

java.net.InetAddress.getLocalHost() – Returns the address of the local host. This is achieved by retrieving the name of the host from the system, then resolving that name into an InetAddress.

java.net.InetAddress.getHostAddress() – Returns the IP address string in textual presentation.

java.net.InetAddress.getHostName() – Gets the host name for this IP address.

 

package com.technicalkeeda.app;
 
import java.net.InetAddress;
 
class IPAddressExample {
    public static void main(String args[]) throws Exception {
        InetAddress inetAddress = InetAddress.getLocalHost();
        System.out.println("IP Address:- " + inetAddress.getHostAddress());
        System.out.println("Host Name:- " + inetAddress.getHostName());
    }
}

output

IP Address:- 169.254.151.193
Host Name:- swami-samartha

Related searches

How to Find IP address of localhost or a Server in Java? Example

In today’s Java programming tutorial, we will learn some networking basics by exploring the java.net package. One of the simple Java network programming exercises, yet very useful, is to write a program to find the IP address of the local host in Java. Sometimes this question is also asked to find the IP address of the Server on which your Java program is running or find the IP address of your machine using Java etc. In short, they all refer to localhost. For those who are entirely new in the networking space, there are two things to identify a machine in a network, which could be LAN, WAN, or The Internet.

The first thing is the DNS name and the second thing is the IP address. In Local Area Network, DNS is more generally replaced by hostname, which could be as simple as ReportingServer to ReportingServer.com or something else.

Both these hostname and IP addresses are related to each other, which means given hostname, your computer can find an IP address and vice-versa. The file they use for a hostname to IP address resolution is /etc/host in both Windows 8 and Linux. Java provides API to get this IP address by providing hostname.

Tag: Get Local IP Address and Hostname In Java, get ip address using java, get hostname using java

Related searches

Scroll to Top