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>
相关推荐
树℡独8 小时前
ns-3仿真之应用层(五)
服务器·网络·tcp/ip·ns3
zhang133830890759 小时前
CG-09H 超声波风速风向传感器 加热型 ABS材质 重量轻 没有机械部件
大数据·运维·网络·人工智能·自动化
a41324479 小时前
ubuntu 25 安装vllm
linux·服务器·ubuntu·vllm
Configure-Handler9 小时前
buildroot System configuration
java·服务器·数据库
津津有味道9 小时前
易语言TCP服务端接收刷卡数据并向客户端读卡器发送指令
服务器·网络协议·tcp·易语言
Fᴏʀ ʏ꯭ᴏ꯭ᴜ꯭.10 小时前
Keepalived VIP迁移邮件告警配置指南
运维·服务器·笔记
酣大智10 小时前
接口模式参数
运维·网络·网络协议·tcp/ip
Genie cloud10 小时前
1Panel SSL证书申请完整教程
服务器·网络协议·云计算·ssl
!chen11 小时前
linux服务器静默安装Oracle26ai
linux·运维·服务器
莫大33011 小时前
2核2G云服务器PHP8.5+MySQL9.0+Nginx(LNMP)安装WordPress网站详细教程
运维·服务器·nginx