Languages
[Edit]
EN

Java - get host name and IP address of local machine

6 points
Created by:
Argon
617

In this short article, we would like to show how to get localhost host name and IP address using Java.

Quick solution:

// import java.net.InetAddress;

InetAddress address = InetAddress.getLocalHost();
    	
String hostName = address.getHostName();
String hostAddress = address.getHostAddress();  // IPv4 or IPv6

 

Simple example

import java.net.InetAddress;

public class Program {
	
    public static void main(String[] args) throws Exception {
	
    	InetAddress address = InetAddress.getLocalHost();
    	
    	System.out.println("My host name is:  " + address.getHostName());
        System.out.println("My IP address is: " + address.getHostAddress());
	}
}

Example output:

My host name is:  DESKTOP-U147DNR
My IP address is: 192.168.56.1

 

Complex example

import java.net.InetAddress;
import java.net.NetworkInterface;
import java.util.Enumeration;

public class Program {
	
    public static void main(String[] args) throws Exception {

        printNetworkInterfaces(NetworkInterface.getNetworkInterfaces());
	}

    private static void printNetworkInterfaces(Enumeration<NetworkInterface> networkInterfaces) {
        while (networkInterfaces.hasMoreElements()) {
            NetworkInterface networkInterface = networkInterfaces.nextElement();
            System.out.println("Interface name: " + networkInterface.getName());
            printInetAddresses(networkInterface.getInetAddresses());
        }
    }

    private static void printInetAddresses(Enumeration<InetAddress> inetAddresses) {
        while (inetAddresses.hasMoreElements()) {
            InetAddress inetAddress = inetAddresses.nextElement();
            System.out.println("                " + inetAddress.getHostName() + "  " + inetAddress.getHostAddress());
        }
    }
}

Example output:

Interface name: lo
                127.0.0.1  127.0.0.1
                0:0:0:0:0:0:0:1  0:0:0:0:0:0:0:1
Interface name: eth0
                DESKTOP-U147DNR  192.168.56.1
                DESKTOP-U147DNR  fe80:0:0:0:8c21:8c20:8ae8:fd66%eth0
Interface name: wlan0
                DESKTOP-U147DNR.home  192.168.1.113
                80fe:0:0:0:5522:2db2:7ea1:4c44%wlan0  80fe:0:0:0:5522:2db2:7ea1:4c44%wlan0

 

Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join