Preface
How to accurately obtain the local IP address in Java? Most of the methods on the Internet are InetAddress.getLocalHost().getHostAddress()
. This can indeed obtain the local IP address, but it is inaccurate. Because one problem has been ignored, the network environment is changeable. Different network cards on a computer have multiple IP addresses, such as Lan, WiFi, Bluetooth, hotspots, virtual machine network cards, etc.
1. Rules
127.xxx.xxx.xxx belongs to the "loopback" address, that is, it can only be seen by your own machine. It is the address of this machine. Compare Common ones are 127.0.0.1
192.168.xxx.xxx, which belongs to the private private address (site local address) and is accessible within the local organization and can only be seen on the local LAN
Similarly, 10.xxx.xxx.xxx, from 172.16.xxx.xxx to 172.31.xxx.xxx are all private addresses and belong to internal access of the organization
169.254.xxx.xxx belongs to the link local IP and is available in a single network segment.
From 224.xxx.xxx.xxx to 239.xxx.xxx.xxx belongs to the group Broadcast address
The special 255.255.255.255 belongs to the broadcast address
The other addresses are point-to-point available public IPv4 addresses
2. Obtain
1.Use
public static void main(String[] args) throws SocketException { System.out.println( IpUtil.getLocalIp4Address().get().toString().replaceAll("/","")); }
2.Tool class
package com.dingwen.test.utils; import org.springframework.util.ObjectUtils; import java.net.*; import java.util.ArrayList; import java.util.Enumeration; import java.util.List; import java.util.Optional; /** * 获取本机IP 地址 * * @author dingwen * 2021.04.28 11:49 */ public class IpUtil { /* * 获取本机所有网卡信息 得到所有IP信息 * @return Inet4Address> */ public static List<Inet4Address> getLocalIp4AddressFromNetworkInterface() throws SocketException { List<Inet4Address> addresses = new ArrayList<>(1); // 所有网络接口信息 Enumeration<NetworkInterface> networkInterfaces = NetworkInterface.getNetworkInterfaces(); if (ObjectUtils.isEmpty(networkInterfaces)) { return addresses; } while (networkInterfaces.hasMoreElements()) { NetworkInterface networkInterface = networkInterfaces.nextElement(); //滤回环网卡、点对点网卡、非活动网卡、虚拟网卡并要求网卡名字是eth或ens开头 if (!isValidInterface(networkInterface)) { continue; } // 所有网络接口的IP地址信息 Enumeration<InetAddress> inetAddresses = networkInterface.getInetAddresses(); while (inetAddresses.hasMoreElements()) { InetAddress inetAddress = inetAddresses.nextElement(); // 判断是否是IPv4,并且内网地址并过滤回环地址. if (isValidAddress(inetAddress)) { addresses.add((Inet4Address) inetAddress); } } } return addresses; } /** * 过滤回环网卡、点对点网卡、非活动网卡、虚拟网卡并要求网卡名字是eth或ens开头 * * @param ni 网卡 * @return 如果满足要求则true,否则false */ private static boolean isValidInterface(NetworkInterface ni) throws SocketException { return !ni.isLoopback() && !ni.isPointToPoint() && ni.isUp() && !ni.isVirtual() && (ni.getName().startsWith("eth") || ni.getName().startsWith("ens")); } /** * 判断是否是IPv4,并且内网地址并过滤回环地址. */ private static boolean isValidAddress(InetAddress address) { return address instanceof Inet4Address && address.isSiteLocalAddress() && !address.isLoopbackAddress(); } /* * 通过Socket 唯一确定一个IP * 当有多个网卡的时候,使用这种方式一般都可以得到想要的IP。甚至不要求外网地址8.8.8.8是可连通的 * @return Inet4Address> */ private static Optional<Inet4Address> getIpBySocket() throws SocketException { try (final DatagramSocket socket = new DatagramSocket()) { socket.connect(InetAddress.getByName("8.8.8.8"), 10002); if (socket.getLocalAddress() instanceof Inet4Address) { return Optional.of((Inet4Address) socket.getLocalAddress()); } } catch (UnknownHostException networkInterfaces) { throw new RuntimeException(networkInterfaces); } return Optional.empty(); } /* * 获取本地IPv4地址 * @return Inet4Address> */ public static Optional<Inet4Address> getLocalIp4Address() throws SocketException { final List<Inet4Address> inet4Addresses = getLocalIp4AddressFromNetworkInterface(); if (inet4Addresses.size() != 1) { final Optional<Inet4Address> ipBySocketOpt = getIpBySocket(); if (ipBySocketOpt.isPresent()) { return ipBySocketOpt; } else { return inet4Addresses.isEmpty() ? Optional.empty() : Optional.of(inet4Addresses.get(0)); } } return Optional.of(inet4Addresses.get(0)); } }
Reference:
https ://www.jianshu.com/p/f619663f0f0a
https://www.cnblogs.com/starcrm/p/7071227.html
The following is a piece of Java to get the local IP Example code for address
import java.net.*; import java.util.ArrayList; import java.util.Enumeration; import java.util.List; import java.util.Objects; import java.util.Optional; /** * 获取本机IP 地址 */ public class IpUtil { /* * 获取本机所有网卡信息 得到所有IP信息 * @return Inet4Address> */ public static List<Inet4Address> getLocalIp4AddressFromNetworkInterface() throws SocketException { List<Inet4Address> addresses = new ArrayList<>(1); // 所有网络接口信息 Enumeration<NetworkInterface> networkInterfaces = NetworkInterface.getNetworkInterfaces(); if (Objects.isNull(networkInterfaces)) { return addresses; } while (networkInterfaces.hasMoreElements()) { NetworkInterface networkInterface = networkInterfaces.nextElement(); //滤回环网卡、点对点网卡、非活动网卡、虚拟网卡并要求网卡名字是eth或ens开头 if (!isValidInterface(networkInterface)) { continue; } // 所有网络接口的IP地址信息 Enumeration<InetAddress> inetAddresses = networkInterface.getInetAddresses(); while (inetAddresses.hasMoreElements()) { InetAddress inetAddress = inetAddresses.nextElement(); // 判断是否是IPv4,并且内网地址并过滤回环地址. if (isValidAddress(inetAddress)) { addresses.add((Inet4Address) inetAddress); } } } return addresses; } /** * 过滤回环网卡、点对点网卡、非活动网卡、虚拟网卡并要求网卡名字是eth或ens开头 * * @param ni 网卡 * @return 如果满足要求则true,否则false */ private static boolean isValidInterface(NetworkInterface ni) throws SocketException { return !ni.isLoopback() && !ni.isPointToPoint() && ni.isUp() && !ni.isVirtual() && (ni.getName().startsWith("eth") || ni.getName().startsWith("ens")); } /** * 判断是否是IPv4,并且内网地址并过滤回环地址. */ private static boolean isValidAddress(InetAddress address) { return address instanceof Inet4Address && address.isSiteLocalAddress() && !address.isLoopbackAddress(); } /* * 通过Socket 唯一确定一个IP * 当有多个网卡的时候,使用这种方式一般都可以得到想要的IP。甚至不要求外网地址8.8.8.8是可连通的 * @return Inet4Address> */ private static Optional<Inet4Address> getIpBySocket() throws SocketException { try (final DatagramSocket socket = new DatagramSocket()) { socket.connect(InetAddress.getByName("8.8.8.8"), 10002); if (socket.getLocalAddress() instanceof Inet4Address) { return Optional.of((Inet4Address) socket.getLocalAddress()); } } catch (UnknownHostException networkInterfaces) { throw new RuntimeException(networkInterfaces); } return Optional.empty(); } /* * 获取本地IPv4地址 * @return Inet4Address> */ public static Optional<Inet4Address> getLocalIp4Address() throws SocketException { final List<Inet4Address> inet4Addresses = getLocalIp4AddressFromNetworkInterface(); if (inet4Addresses.size() != 1) { final Optional<Inet4Address> ipBySocketOpt = getIpBySocket(); if (ipBySocketOpt.isPresent()) { return ipBySocketOpt; } else { return inet4Addresses.isEmpty() ? Optional.empty() : Optional.of(inet4Addresses.get(0)); } } return Optional.of(inet4Addresses.get(0)); } }
The above is the detailed content of How to write the code to obtain the local IP address in Java. For more information, please follow other related articles on the PHP Chinese website!

本篇文章给大家带来了关于java的相关知识,其中主要介绍了关于结构化数据处理开源库SPL的相关问题,下面就一起来看一下java下理想的结构化数据处理类库,希望对大家有帮助。

本篇文章给大家带来了关于java的相关知识,其中主要介绍了关于PriorityQueue优先级队列的相关知识,Java集合框架中提供了PriorityQueue和PriorityBlockingQueue两种类型的优先级队列,PriorityQueue是线程不安全的,PriorityBlockingQueue是线程安全的,下面一起来看一下,希望对大家有帮助。

本篇文章给大家带来了关于java的相关知识,其中主要介绍了关于java锁的相关问题,包括了独占锁、悲观锁、乐观锁、共享锁等等内容,下面一起来看一下,希望对大家有帮助。

本篇文章给大家带来了关于java的相关知识,其中主要介绍了关于多线程的相关问题,包括了线程安装、线程加锁与线程不安全的原因、线程安全的标准类等等内容,希望对大家有帮助。

本篇文章给大家带来了关于java的相关知识,其中主要介绍了关于枚举的相关问题,包括了枚举的基本操作、集合类对枚举的支持等等内容,下面一起来看一下,希望对大家有帮助。

本篇文章给大家带来了关于Java的相关知识,其中主要介绍了关于关键字中this和super的相关问题,以及他们的一些区别,下面一起来看一下,希望对大家有帮助。

本篇文章给大家带来了关于java的相关知识,其中主要介绍了关于平衡二叉树(AVL树)的相关知识,AVL树本质上是带了平衡功能的二叉查找树,下面一起来看一下,希望对大家有帮助。

封装是一种信息隐藏技术,是指一种将抽象性函式接口的实现细节部分包装、隐藏起来的方法;封装可以被认为是一个保护屏障,防止指定类的代码和数据被外部类定义的代码随机访问。封装可以通过关键字private,protected和public实现。


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

Dreamweaver CS6
Visual web development tools

SublimeText3 Linux new version
SublimeText3 Linux latest version

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),
