Site icon

Program get localhost IPAddress & Hostname in java (example)

Problem Statement?

Methods of InetAddress class to get network details

Method Name Description
String getCanonicalHostName() Gets the fully qualified domain name for this IP address.
String getHostAddress() Returns the IP address string in textual presentation.
String getHostName() Gets the host name for this IP address

Examples: Get IPAddress, hostname & canonical name in java

Example: get host details for localhost
InetAddress localHost = InetAddress.getLocalHost() 

Output: Program should return host like 
HostName is :<my dummy hostname>
Canonical hostname is: <my fully qualified hostname>
IPAddress is :<IP address of localhost>

Program: Network info hostname, IP Address & Canonical name in java

package org.learn.network;

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

public class HostNameAndIPAddressDemo {

    public static void main(String[] args) throws UnknownHostException {
        final InetAddress localHost = InetAddress.getLocalHost();

        String canonicalHostName = localHost.getCanonicalHostName();
        String hostname = localHost.getCanonicalHostName();
        String ipAddress = localHost.getHostAddress();

        System.out.println("HostName is :"+hostname);
        System.out.println("Canonical hostname is:"+canonicalHostName);
        System.out.println("IPAddress is :"+ipAddress);
    }
}

Output: Network information for localhost in java

HostName is :MyHostName-domainserver.com
Canonical hostname is:MyHostName-domainserver.com
IPAddress is :192.128.26.215
Exit mobile version