Java Local Address Get getLocalAddress(String filter)

Here you can find the source of getLocalAddress(String filter)

Description

get Local Address

License

Apache License

Declaration

public static String getLocalAddress(String filter) 

Method Source Code


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

import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.Enumeration;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Main {
    public static String getLocalAddress(String filter) {
        if (filter == null) {
            InetAddress addr;//w  w  w  .jav a  2  s .com
            try {
                addr = InetAddress.getLocalHost();
                return addr.getHostAddress().toString();
            } catch (UnknownHostException e) {
                throw new RuntimeException("Failed to getLocalAddress", e);
            }
        }
        Pattern filterPattern = Pattern.compile(filter);
        try {
            Enumeration<NetworkInterface> networks = NetworkInterface.getNetworkInterfaces();
            while (networks.hasMoreElements()) {
                NetworkInterface network = networks.nextElement();
                Enumeration<InetAddress> addresses = network.getInetAddresses();
                while (addresses.hasMoreElements()) {
                    String address = addresses.nextElement().getHostAddress();
                    Matcher m = filterPattern.matcher(address);
                    if (m.matches()) {
                        return address;
                    }
                }
            }
        } catch (SocketException e) {
            throw new RuntimeException("Failed to getLocalAddress", e);
        }
        throw new RuntimeException("Failed to getLocalAddress");
    }
}

Related

  1. getLocalAddress(final String start, final String end)
  2. getLocalAddress(int port)
  3. getLocalAddress(int port)
  4. getLocalAddress(int port)
  5. getLocalAddress(String adaptorName)
  6. getLocalAddress0()
  7. getLocalAddressAsString()
  8. getLocalAddresses()
  9. getLocalAddresses()