All Downloads are FREE. Search and download functionalities are using the official Maven repository.

eleme.openapi.sdk.media.utils.IpUtils Maven / Gradle / Ivy

There is a newer version: 1.30.71
Show newest version
package eleme.openapi.sdk.media.utils;

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

/**
 * Created by huamulou on 15/12/13.
 */
public class IpUtils {

    static String LOCAL_IP;

    public final static String getIpAddress() {
        if (LOCAL_IP == null) {
            synchronized (IpUtils.class) {
                if (LOCAL_IP == null) {
                    LOCAL_IP = getIpAddressInternal();
                }
            }
        }
        return LOCAL_IP;
    }


    private final static String getIpAddressInternal() {
        String localip = null;// 本地IP,如果没有配置外网IP则返回它
        String netip = null;// 外网IP

        Enumeration netInterfaces;
        try {
            netInterfaces = NetworkInterface.getNetworkInterfaces();
        } catch (SocketException e) {
            throw new RuntimeException("Can't find the localIP!");
        }
        InetAddress ip;
        boolean finded = false;// 是否找到外网IP
        while (netInterfaces.hasMoreElements() && !finded) {
            NetworkInterface ni = netInterfaces.nextElement();
            try {
                if (!ni.isLoopback()) {
                    Enumeration address = ni.getInetAddresses();
                    while (address.hasMoreElements()) {
                        ip = address.nextElement();
                        if (!ip.isSiteLocalAddress()
                                && !ip.isLoopbackAddress()
                                && !ip.getHostAddress().contains(":")) {// 外网IP
                            netip = ip.getHostAddress();
                            finded = true;
                            break;
                        } else if (ip.isSiteLocalAddress()
                                && !ip.isLoopbackAddress()
                                && !ip.getHostAddress().contains(":")) {// 内网IP
                            localip = ip.getHostAddress();
                        }
                    }
                }
            } catch (SocketException e) {
            }
        }

        if (localip != null && !"".equals(localip)) {
            return localip;
        } else {
            return netip;
        }
    }

}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy