通过终端跟java代码的方式查询自身的ip地址

一、查看自身ip
linux的cmd窗口输入 ifconfig
windows的终端输入 ipconfig

java代码:

public static String getIpAddress() {
    try {
        Enumeration<NetworkInterface> allNetInterfaces = NetworkInterface.getNetworkInterfaces();
        InetAddress ip;
        while (allNetInterfaces.hasMoreElements()) {
            NetworkInterface netInterface = allNetInterfaces.nextElement();
            if (netInterface.isLoopback() || netInterface.isVirtual() || !netInterface.isUp()) {
                continue;
            } else {
                Enumeration<InetAddress> addresses = netInterface.getInetAddresses();
                while (addresses.hasMoreElements()) {
                    ip = addresses.nextElement();
                    if (ip != null && ip instanceof Inet4Address) {
                        return ip.getHostAddress();
                    }
                }
            }
        }
    } catch (Exception e) {
        System.err.println("IP地址获取失败" + e);
    }
    return "";
}

二、查看出口ip,也就是外网ip
curl ifconfig.me
curl ipinfo.io/ip
curl ip.sb
curl icanhazip.com
curl http://icanhazip.com
curl http://ip.3322.net
curl https://httpbin.org/ip
curl -s http://httpbin.org/ip
都是通过curl的方式windows以及linux都适应

java代码:

    public static String getExternalIP() {
        String ipServiceUrl = "http://api.ipify.org";
        try {
            URL url = new URL(ipServiceUrl);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("GET");
            if (connection.getResponseCode() == 200) {
                BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
                String ip = in.readLine(); 
                in.close();
                return ip;
            } else {
                System.out.println("IP地址获取失败");
                return null;
            }
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值