获取本机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]

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值