当前位置: 首页 > news >正文

Java 工具类 IpUtil - 获取本机所有 IP 地址,LocalHost 对应地址 IP

Java 工具类 IpUtil - 获取本机所有 IP 地址,LocalHost 对应地址 IP

IP 工具类

源代码:

/**
 * <p>
 *
 * @author XiaoPengwei
 * @since 2019-07-20
 */
import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.Enumeration;


public class IpUtil {

    public static void main(String[] args) {

        IpUtil testGetIP = new IpUtil();

        System.out.println("Your LocalHost IP(ipv4) is:");

        System.out.println(testGetIP.getIP());

        System.out.println("\nHere are all your IPS:");
        testGetIP.printAllIp();
    }

    /**
     * Fond LocalHost ipv4
     *
     * @return java.lang.String
     */
    public String getIP() {
        try {
            // 根据 hostname 找 ip
            InetAddress address = InetAddress.getLocalHost();
            if (address.isLoopbackAddress()) {
                Enumeration<NetworkInterface> allNetInterfaces = NetworkInterface.getNetworkInterfaces();
                while (allNetInterfaces.hasMoreElements()) {
                    NetworkInterface netInterface = allNetInterfaces.nextElement();
                    Enumeration<InetAddress> addresses = netInterface.getInetAddresses();
                    while (addresses.hasMoreElements()) {
                        InetAddress ip = addresses.nextElement();
                        if (!ip.isLinkLocalAddress() && !ip.isLoopbackAddress() && ip instanceof Inet4Address) {
                            return ip.getHostAddress();
                        }
                    }
                }
            }
            return address.getHostAddress();
        } catch (UnknownHostException | SocketException e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * Find all network interfaces
     */
    public void printAllIp() {
        try {
            Enumeration<NetworkInterface> allNetInterfaces = NetworkInterface.getNetworkInterfaces();
            while (allNetInterfaces.hasMoreElements()) {
                NetworkInterface netInterface = allNetInterfaces.nextElement();

                // Remove loopback interface, sub-interface, unrun and interface
                if (netInterface.isLoopback() || netInterface.isVirtual() || !netInterface.isUp()) {
                    continue;
                }

                Enumeration<InetAddress> addresses = netInterface.getInetAddresses();
                while (addresses.hasMoreElements()) {
                    InetAddress ip = addresses.nextElement();
                    if (ip != null) {

                        System.out.println("ip = " + ip.getHostAddress());
                        // ipv4
                        if (ip instanceof Inet4Address) {
                            System.out.println("ipv4 = " + ip.getHostAddress());

                            if (!ip.getHostAddress().startsWith("192") && !ip.getHostAddress().startsWith("10") && !ip.getHostAddress().startsWith("172")) {
                                // Intranet
                                ip.getHostAddress();
                            }
                        }
                    }
                }
            }
        } catch (SocketException e) {
            System.err.println("[Error] can't get host ip address" + e.getMessage());
        }
    }
}

相关文章:

  • 8080 端口被占用的解决方法 netstat -ano;taskkill (命令行)
  • 手写 Spring MVC
  • Oracle 在 Drop 表时的 Cascade Constraints
  • Oracle:ORA-01219:database not open:queries allowed on fixed tables/views only
  • MyBatis: Invalid bound statement (not found) 错误的可能原因
  • Git 删除已经 Push 的远程文件夹或文件的命令方法
  • 写给自己 - 开发路上
  • ubuntu 18 自带截图工具 - 快捷键
  • svn 必须会敲的常用命令
  • ubuntu 18 解锁文件目录(谨慎操作)
  • ubuntu 18 安装 navicat Premium 中文乱码(很彻底)
  • 在 ubuntu 18 中为 navicat 创建快捷方式
  • You have not concluded your cherry-pick (CHERRY_PICK_HEAD exists).Please, commit your changes
  • Ubuntu 18 使用命令卸载软件
  • Ubuntu 18 系统时间问题 - 解决其使用 BIOS 时间,不联网同步
  • 【EOS】Cleos基础
  • axios请求、和返回数据拦截,统一请求报错提示_012
  • download使用浅析
  • LeetCode541. Reverse String II -- 按步长反转字符串
  • Linux各目录及每个目录的详细介绍
  • Python 反序列化安全问题(二)
  • QQ浏览器x5内核的兼容性问题
  • React 快速上手 - 07 前端路由 react-router
  • SQL 难点解决:记录的引用
  • Travix是如何部署应用程序到Kubernetes上的
  • Vue2.0 实现互斥
  • vue2.0一起在懵逼的海洋里越陷越深(四)
  • 力扣(LeetCode)357
  • 入门级的git使用指北
  • 使用Envoy 作Sidecar Proxy的微服务模式-4.Prometheus的指标收集
  • 数组大概知多少
  • 我建了一个叫Hello World的项目
  • ​LeetCode解法汇总2670. 找出不同元素数目差数组
  • #中的引用型是什么意识_Java中四种引用有什么区别以及应用场景
  • (1)Android开发优化---------UI优化
  • (1/2)敏捷实践指南 Agile Practice Guide ([美] Project Management institute 著)
  • (2)STM32单片机上位机
  • (3)nginx 配置(nginx.conf)
  • (6)【Python/机器学习/深度学习】Machine-Learning模型与算法应用—使用Adaboost建模及工作环境下的数据分析整理
  • (DFS + 剪枝)【洛谷P1731】 [NOI1999] 生日蛋糕
  • (Redis使用系列) SpringBoot中Redis的RedisConfig 二
  • (办公)springboot配置aop处理请求.
  • (编译到47%失败)to be deleted
  • (动手学习深度学习)第13章 计算机视觉---图像增广与微调
  • (学习日记)2024.03.12:UCOSIII第十四节:时基列表
  • (转)详解PHP处理密码的几种方式
  • .md即markdown文件的基本常用编写语法
  • .NET CORE 3.1 集成JWT鉴权和授权2
  • .net MySql
  • .NET Remoting学习笔记(三)信道
  • .NET 跨平台图形库 SkiaSharp 基础应用
  • .net开源工作流引擎ccflow表单数据返回值Pop分组模式和表格模式对比
  • @Autowired注解的实现原理
  • @Bean有哪些属性
  • @Not - Empty-Null-Blank