获取本机IP地址(Java版本)

获取本机IP地址(Java版本)—Java版本

代码如下:

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;

/**
 * 获取当前运行环境的ip地址
 * */
public class NetUtils {
    private static final Logger logger = LoggerFactory.getLogger(NetUtils.class);

    public static int scoreAddr(NetworkInterface iface, InetAddress addr) {
        int score = 0;
        if (addr instanceof Inet4Address) {
            score += 300;
        }
        try {
            if (!iface.isLoopback() && !addr.isLoopbackAddress()) {
                score += 100;
                if (iface.isUp()) {
                    score += 100;
                }
            }
        } catch (SocketException e) {
            e.printStackTrace();
            logger.error("Unable to score IP {} of interface {}", addr, iface, e);
        }

        return score;
    }

    public static InetAddress getCurrentIp() {
        int bestScore = -1;
        InetAddress bestAddr = null;

        try {
            Enumeration<NetworkInterface> networkInterfaces = NetworkInterface.getNetworkInterfaces();
            while (networkInterfaces.hasMoreElements()) {
                NetworkInterface iface = (NetworkInterface) networkInterfaces.nextElement();
                Enumeration<InetAddress> addrs = iface.getInetAddresses();

                while (addrs.hasMoreElements()) {
                    InetAddress addr = (InetAddress) addrs.nextElement();
                    int score = scoreAddr(iface, addr);
                    if (score >= bestScore) {
                        bestScore = score;
                        bestAddr = addr;
                    }
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
            logger.error("Problem getting local IP", e);
        }

        return bestAddr;
    }

    public static void main(String[] args) {
        String ip = NetUtils.getCurrentIp().getHostAddress();
        System.out.println(ip);
    }

}

[END]

猜你喜欢

转载自blog.csdn.net/qian_feifei/article/details/75195003