Java Program to Print All Local IP Addresses

in #java5 years ago

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)

Reposted to Blog

^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Thank you for reading ^^^^^^^^^^^^^^^

NEW! Following my Trail (Upvote or/and Downvote)

Follow me for topics of Algorithms, Blockchain and Cloud.
I am @justyy - a Steem Witness
https://steemyy.com

My contributions

Delegation Service

Important Update of Delegation Service!

  • Delegate 1000 to justyy: Link
  • Delegate 5000 to justyy: Link
  • Delegate 10000 to justyy: Link

Support me

If you like my work, please:

  1. Delegate SP: https://steemyy.com/sp-delegate-form/?delegatee=justyy
  2. Vote @justyy as Witness: https://steemyy.com/witness-voting/?witness=justyy&action=approve
  3. Set @justyy as Proxy: https://steemyy.com/witness-voting/?witness=justyy&action=proxy
    Alternatively, you can vote witness or set proxy here: https://steemit.com/~witnesses

Coin Marketplace

STEEM 0.04
TRX 0.32
JST 0.084
BTC 60162.63
ETH 1576.76
USDT 1.00
SBD 0.42