Java IP Address Get getIPFromInterface(String ni)

Here you can find the source of getIPFromInterface(String ni)

Description

get IP From Interface

License

LGPL

Declaration

public static String getIPFromInterface(String ni) throws UnknownHostException, SocketException 

Method Source Code


//package com.java2s;
//License from project: LGPL 

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

public class Main {
    public static String getIPFromInterface(String ni) throws UnknownHostException, SocketException {

        if (ni.equals("lo")) {
            return InetAddress.getLocalHost().getHostAddress();
        }/*  ww w.  j a v a  2 s .c  om*/

        //other Network interfaces
        Enumeration<NetworkInterface> n = NetworkInterface.getNetworkInterfaces();
        for (; n.hasMoreElements();) {
            NetworkInterface e = n.nextElement();

            if (e.getDisplayName().equals(ni)) {
                return getIPAddress(e);
            }

        }

        return null;
    }

    public static String getIPAddress(NetworkInterface e) {
        Enumeration<InetAddress> a = e.getInetAddresses();
        for (; a.hasMoreElements();) {
            InetAddress addr = a.nextElement(); //IPv6 
            addr = a.nextElement(); //IPv4

            return addr.getHostAddress();

        }

        return null;
    }
}

Related

  1. getIpByHost(String hostName)
  2. getIPByInterfaceName(String name)
  3. getIpByName(String name)
  4. getIpByNetworkInterfaceName(String name)
  5. getIPFromHash(final long ipHash)
  6. getIPFromNetworkInterface()
  7. getIpHostnameLocal()
  8. getIPList(String address)
  9. getIPList(String s, String s1)