Java IP Address Get getIPByInterfaceName(String name)

Here you can find the source of getIPByInterfaceName(String name)

Description

Find the IPv4 address applicable to a given interface name

License

Open Source License

Parameter

Parameter Description
name the name of the interface

Exception

Parameter Description
SocketException an exception

Return

the IPv4 ( ) address defined for the interface or null if not found

Declaration

public static String getIPByInterfaceName(String name) throws SocketException 

Method Source Code


//package com.java2s;
//License from project: Open Source License 

import java.net.Inet4Address;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Collections;
import java.util.Enumeration;
import java.util.Optional;

public class Main {
    /**/*from ww  w.j  a  va2 s  .  com*/
     * Find the IPv4 address applicable to a given interface name
     * 
     * @param name
     *            the name of the interface
     * @return the IPv4 ({@link Inet4Address}) address defined for the interface
     *         or <code>null</code> if not found
     * @throws SocketException
     */
    public static String getIPByInterfaceName(String name) throws SocketException {
        Enumeration<NetworkInterface> nets = NetworkInterface.getNetworkInterfaces();
        Optional<NetworkInterface> device = Collections.list(nets).stream()
                .filter(i -> i.getName().equalsIgnoreCase(name)).findFirst();
        if (!device.isPresent())
            return null;
        return Collections.list(device.get().getInetAddresses()).stream().filter(v -> v instanceof Inet4Address)
                .map(v -> v.getHostAddress()).findFirst().get();
    }
}

Related

  1. getIPAddressFromNetworkInterfaces()
  2. getIPAdresses()
  3. getIpByHost(String hostName)
  4. getIpByHost(String hostName)
  5. getIpByHost(String hostName)
  6. getIpByName(String name)
  7. getIpByNetworkInterfaceName(String name)
  8. getIPFromHash(final long ipHash)
  9. getIPFromInterface(String ni)