How to write the code to obtain the local IP address in Java
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!

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

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

Java 8 introduces the Stream API, providing a powerful and expressive way to process data collections. However, a common question when using Stream is: How to break or return from a forEach operation? Traditional loops allow for early interruption or return, but Stream's forEach method does not directly support this method. This article will explain the reasons and explore alternative methods for implementing premature termination in Stream processing systems. Further reading: Java Stream API improvements Understand Stream forEach The forEach method is a terminal operation that performs one operation on each element in the Stream. Its design intention is

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

PHP and Python each have their own advantages, and the choice should be based on project requirements. 1.PHP is suitable for web development, with simple syntax and high execution efficiency. 2. Python is suitable for data science and machine learning, with concise syntax and rich libraries.

PHP is suitable for web development, especially in rapid development and processing dynamic content, but is not good at data science and enterprise-level applications. Compared with Python, PHP has more advantages in web development, but is not as good as Python in the field of data science; compared with Java, PHP performs worse in enterprise-level applications, but is more flexible in web development; compared with JavaScript, PHP is more concise in back-end development, but is not as good as JavaScript in front-end development.

PHP and Python each have their own advantages and are suitable for different scenarios. 1.PHP is suitable for web development and provides built-in web servers and rich function libraries. 2. Python is suitable for data science and machine learning, with concise syntax and a powerful standard library. When choosing, it should be decided based on project requirements.

Capsules are three-dimensional geometric figures, composed of a cylinder and a hemisphere at both ends. The volume of the capsule can be calculated by adding the volume of the cylinder and the volume of the hemisphere at both ends. This tutorial will discuss how to calculate the volume of a given capsule in Java using different methods. Capsule volume formula The formula for capsule volume is as follows: Capsule volume = Cylindrical volume Volume Two hemisphere volume in, r: The radius of the hemisphere. h: The height of the cylinder (excluding the hemisphere). Example 1 enter Radius = 5 units Height = 10 units Output Volume = 1570.8 cubic units explain Calculate volume using formula: Volume = π × r2 × h (4

The reasons why PHP is the preferred technology stack for many websites include its ease of use, strong community support, and widespread use. 1) Easy to learn and use, suitable for beginners. 2) Have a huge developer community and rich resources. 3) Widely used in WordPress, Drupal and other platforms. 4) Integrate tightly with web servers to simplify development deployment.

Java is a popular programming language that can be learned by both beginners and experienced developers. This tutorial starts with basic concepts and progresses through advanced topics. After installing the Java Development Kit, you can practice programming by creating a simple "Hello, World!" program. After you understand the code, use the command prompt to compile and run the program, and "Hello, World!" will be output on the console. Learning Java starts your programming journey, and as your mastery deepens, you can create more complex applications.
