java获取电脑公网IP和内网IP

输出结果:

实现代码:

java 复制代码
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;

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

public class ServerIPUtils {

    public static void main(String[] args) {
        System.out.println(getCombinedIp());
        System.out.println(getExternalIp());
        System.out.println(getInternalIp());
    }

    /**
     * 获取拼接的IP地址(外网_内网)
     * 如果外网IP为空或获取失败,则只返回内网IP
     * @return 拼接后的IP地址
     */
    public static String getCombinedIp() {
        String externalIp = getExternalIp();
        String internalIp = getInternalIp();

        // 如果外网IP为空或为unknown,则只返回内网IP
        if (externalIp == null || externalIp.isEmpty()) {
            return internalIp;
        }

        // 否则返回 外网IP_内网IP 的格式
        return externalIp + "_" + internalIp;
    }

    /**
     * 获取内网IP地址
     * @return 内网IP地址
     */
    public static String getInternalIp() {
        try {
            Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
            while (interfaces.hasMoreElements()) {
                NetworkInterface networkInterface = interfaces.nextElement();
                if (networkInterface.isLoopback() || networkInterface.isVirtual() || !networkInterface.isUp()) {
                    continue;
                }

                Enumeration<InetAddress> addresses = networkInterface.getInetAddresses();
                while (addresses.hasMoreElements()) {
                    InetAddress address = addresses.nextElement();
                    String ip = address.getHostAddress();

                    // 跳过IPv6地址和回环地址
                    if (ip.contains(":") || ip.startsWith("127.")) {
                        continue;
                    }

                    // 返回第一个有效的私有IP地址
                    if (isValidIpAddress(ip)) {
                        return ip;
                    }
                }
            }
        } catch (SocketException e) {
            e.printStackTrace();
        }

        return "127.0.0.1"; // 默认返回本地回环地址
    }

    /**
     * 获取外网IP地址
     * @return 外网IP地址
     */
    public static String getExternalIp() {
        // 定义多个获取公网IP的服务URL
        String[] urls = {
                "http://ifconfig.me",
                "http://ifconfig.co",
                "http://icanhazip.com",
                "http://ident.me",
                "http://whatismyip.akamai.com"
        };

        // 尝试每个服务直到成功获取IP
        for (String url : urls) {
            try {
                HttpResponse response = HttpRequest.get(url)
                        .timeout(5000)
                        .execute();

                // 检查响应状态码和内容
                if (response.getStatus() == 200 && response.body() != null) {
                    String ip = response.body().trim();
                    if (!ip.isEmpty() && isValidIpAddress(ip)) {
                        return ip;
                    }
                }
            } catch (Exception e) {
                // 继续尝试下一个服务
                continue;
            }
        }

        return null;
    }


    // 验证IP地址格式是否有效
    private static boolean isValidIpAddress(String ip) {
        if (ip == null || ip.isEmpty()) {
            return false;
        }

        String[] parts = ip.split("\\.");
        if (parts.length != 4) {
            return false;
        }

        for (String part : parts) {
            try {
                int num = Integer.parseInt(part);
                if (num < 0 || num > 255) {
                    return false;
                }
            } catch (NumberFormatException e) {
                return false;
            }
        }

        return true;
    }

}

另外导入hutool包

XML 复制代码
       <dependency>
            <groupId>cn.hutool</groupId>
            <artifactId>hutool-http</artifactId>
            <version>5.8.20</version>
        </dependency>
相关推荐
较劲男子汉4 小时前
CANN Runtime零拷贝传输技术源码实战 彻底打通Host与Device的数据传输壁垒
运维·服务器·数据库·cann
wypywyp4 小时前
8. ubuntu 虚拟机 linux 服务器 TCP/IP 概念辨析
linux·服务器·ubuntu
Doro再努力4 小时前
【Linux操作系统10】Makefile深度解析:从依赖推导到有效编译
android·linux·运维·服务器·编辑器·vim
senijusene4 小时前
Linux软件编程:IO编程,标准IO(1)
linux·运维·服务器
不像程序员的程序媛5 小时前
Nginx日志切分
服务器·前端·nginx
忧郁的橙子.5 小时前
02-本地部署Ollama、Python
linux·运维·服务器
chian-ocean5 小时前
深入 CANN:使用 `tbe-op` 构建自定义高性能算子
网络
醇氧5 小时前
【linux】查看发行版信息
linux·运维·服务器
中议视控5 小时前
可编程网络中央控制系统主机通过红外发射棒控制空调电视等红外设备
网络·物联网·5g
XiaoFan0126 小时前
免密批量抓取日志并集中输出
java·linux·服务器