Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to write the code for Java to get the native IP address?

2025-01-22 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)05/31 Report--

In this article, the editor introduces in detail "how to write the code for Java to obtain the native IP address". The content is detailed, the steps are clear, and the details are handled properly. I hope that this article "how to write the code for Java to obtain the native IP address" can help you solve your doubts.

Preface

How to accurately get the native IP address in Java? Most of the online practices are InetAddress.getLocalHost (). GetHostAddress (). It is true that the native IP address can be obtained, but it is not accurate. Because of ignoring a problem, the network environment is changeable. Different network cards of a computer have multiple IP addresses, Lan, WiFi, Bluetooth, hot spots, virtual machine network cards and so on.

I. rules

127.xxx.xxx.xxx belongs to "loopback" address, that is, it can only be seen on your own machine, that is, the local address. The more common address is 127.0.0.1.

192.168.xxx.xxx belongs to the private private address (site local address), belongs to the internal access of 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 private addresses and are also accessed within the organization.

169.254.xxx.xxx belongs to the connection local address (link local IP) and is available on a separate network segment

From 224.xxx.xxx.xxx to 239.xxx.xxx.xxx belongs to the multicast address

The special 255.255.255.255 belongs to the broadcast address.

The other address is the point-to-point available public IPv4 address

Second, get 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 / * * obtain the local IP address * * @ author dingwen * 2021.04.28 11:49 * / public class IpUtil {/ * * get all the local network card information and get all the IP information * @ return Inet4Address > * / public static List getLocalIp4AddressFromNetworkInterface () throws SocketException {List addresses = new ArrayList (1); / / all network interface information Enumeration networkInterfaces = NetworkInterface.getNetworkInterfaces () If (ObjectUtils.isEmpty (networkInterfaces)) {return addresses;} while (networkInterfaces.hasMoreElements ()) {NetworkInterface networkInterface = networkInterfaces.nextElement (); / / filter back loop Nic, peer-to-peer Nic, inactive Nic, virtual Nic and require the name of the Nic to begin with eth or ens if (! isValidInterface (networkInterface)) {continue } / / IP address information of all network interfaces Enumeration inetAddresses = networkInterface.getInetAddresses (); while (inetAddresses.hasMoreElements ()) {InetAddress inetAddress = inetAddresses.nextElement (); / / determine whether it is IPv4, and the intranet address and filter the loopback address. If (isValidAddress (inetAddress)) {addresses.add ((Inet4Address) inetAddress);} return addresses } / * filter loopback network cards, peer-to-peer network cards, inactive network cards, virtual network cards and require the network card name to start with eth or ens * * @ param ni network card * @ return if the requirement is met, then true Otherwise, 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")) } / * determines whether it is IPv4, and intranet address and filter loopback address. * / private static boolean isValidAddress (InetAddress address) {return address instanceof Inet4Address & & address.isSiteLocalAddress () & &! address.isLoopbackAddress ();} / * determine an IP uniquely through Socket * when there are multiple network cards, you can usually get the desired IP in this way. The public network address 8.8.8.8 is not even required to be reachable * @ return Inet4Address > * / private static Optional 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 ();} / * * obtain the local IPv4 address * @ return Inet4Address > * / public static Optional getLocalIp4Address () throws SocketException {final List inet4Addresses = getLocalIp4AddressFromNetworkInterface () If (inet4Addresses.size ()! = 1) {final Optional 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

Here is a sample code for Java to get the native IP address.

Import java.net.*;import java.util.ArrayList;import java.util.Enumeration;import java.util.List;import java.util.Objects;import java.util.Optional;/** * get the native IP address * / public class IpUtil {/ * * get all the local network card information and get all the IP information * @ return Inet4Address > * / public static List getLocalIp4AddressFromNetworkInterface () throws SocketException {List addresses = new ArrayList (1) / / all network interface information Enumeration networkInterfaces = NetworkInterface.getNetworkInterfaces (); if (Objects.isNull (networkInterfaces)) {return addresses;} while (networkInterfaces.hasMoreElements ()) {NetworkInterface networkInterface = networkInterfaces.nextElement () / / filter back loop network cards, peer-to-peer network cards, inactive network cards, virtual network cards and require the network card name to be eth or ens beginning with if (! isValidInterface (networkInterface)) {continue;} / / IP address information of all network interfaces Enumeration inetAddresses = networkInterface.getInetAddresses () While (inetAddresses.hasMoreElements ()) {InetAddress inetAddress = inetAddresses.nextElement (); / / determines whether it is IPv4, and the intranet address and filter the loopback address. If (isValidAddress (inetAddress)) {addresses.add ((Inet4Address) inetAddress);} return addresses } / * filter loopback network cards, peer-to-peer network cards, inactive network cards, virtual network cards and require the network card name to start with eth or ens * * @ param ni network card * @ return if the requirement is met, then true Otherwise, 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")) } / * determines whether it is IPv4, and intranet address and filter loopback address. * / private static boolean isValidAddress (InetAddress address) {return address instanceof Inet4Address & & address.isSiteLocalAddress () & &! address.isLoopbackAddress ();} / * determine an IP uniquely through Socket * when there are multiple network cards, you can usually get the desired IP in this way. The public network address 8.8.8.8 is not even required to be reachable * @ return Inet4Address > * / private static Optional 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 ();} / * * obtain the local IPv4 address * @ return Inet4Address > * / public static Optional getLocalIp4Address () throws SocketException {final List inet4Addresses = getLocalIp4AddressFromNetworkInterface () If (inet4Addresses.size ()! = 1) {final Optional ipBySocketOpt = getIpBySocket (); if (ipBySocketOpt.isPresent ()) {return ipBySocketOpt;} else {return inet4Addresses.isEmpty ()? Optional.empty (): Optional.of (inet4Addresses.get (0));}} return Optional.of (inet4Addresses.get (0)) }} after reading this, the article "how to write the code for Java to obtain the local IP address" has been introduced. If you want to master the knowledge points of this article, you still need to practice and use it yourself. If you want to know more about related articles, please follow the industry information channel.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report