Java IP Address Get getLocalHostIp()

Here you can find the source of getLocalHostIp()

Description

get Local Host Ip

License

Apache License

Declaration

public static String getLocalHostIp() 

Method Source Code

//package com.java2s;
/*//from w  w  w.  j a va2s  .c  o  m
 * Copyright 2015 lixiaobo
 *
 * VersionUpgrade project licenses this file to you under the Apache License,
 * version 2.0 (the "License"); you may not use this file except in compliance
 * with the License. You may obtain a copy of the License at:
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations
 * under the License.
 */

import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;

import java.util.Enumeration;

public class Main {
    public static String getLocalHostIp() {
        String regex = "[\\d]+.[\\d]+.[\\d]+.[\\d]+";
        Enumeration<?> e = null;
        try {
            e = NetworkInterface.getNetworkInterfaces();
        } catch (SocketException e1) {
            e1.printStackTrace();
        }
        while (e.hasMoreElements()) {
            NetworkInterface n = (NetworkInterface) e.nextElement();
            Enumeration<?> ee = n.getInetAddresses();
            while (ee.hasMoreElements()) {
                InetAddress i = (InetAddress) ee.nextElement();
                String ip = i.getHostAddress();
                if (ip.matches(regex) && !ip.equals("127.0.0.1")) {
                    return ip;
                }
            }
        }
        return null;
    }
}

Related

  1. getIpv6List()
  2. getLanIPAddress()
  3. getLinuxIPAddress()
  4. getLocalAddresses(boolean ipv4only)
  5. getLocalHostIp()
  6. getLocalHostIP()
  7. getLocalhostIp()
  8. getLocalHostIPAdress()
  9. getLocalHostIps()