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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 | 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()); } } } |
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:
1 2 3 4 | 127.0.0.1 192.168.1.94 192.168.56.1 172.28.224.1 |
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) —
GD Star Rating
loading...
191 wordsloading...
Last 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