We can use the following Java command line program to print all loacal IP addresses of the computer. We iterate over all Net-Interfaces and get Inet Addresses.
package com.helloacm;
import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
public class Main {
public static void main(String[] args) {
try {
var allNetInterfaces = NetworkInterface.getNetworkInterfaces();
InetAddress ip = null;
while (allNetInterfaces.hasMoreElements()) {
var netInterface = (NetworkInterface) allNetInterfaces.nextElement();
var addresses = netInterface.getInetAddresses();
while (addresses.hasMoreElements()) {
ip = (InetAddress) addresses.nextElement();
if (ip != null && ip instanceof Inet4Address) {
System.out.println(ip.getHostAddress());
}
}
}
} catch (Exception e) {
System.err.println(e.getMessage());
}
}
}
Example output from the command line:
127.0.0.1
192.168.1.94
192.168.56.1
172.28.224.1
See also: The DNS Lookup Tool in Java (InetAddress)
–EOF (The Ultimate Computing & Technology Blog) —
174 wordsLast Post: Teaching Kids Programming - Algorithms to Check if a Linked List is Palindrome
Next Post: A Pseudo Random Generator in Java to Shuffle an Array/List