There are many ways to get local IP addresses in Java. Here are a few common methods:
1. Use the InetAddress class
InetAddress
Classes are classes used in the Java standard library to represent IP addresses, and you can obtain the IP address of the local host.
import ; import ; public class Main { public static void main(String[] args) { try { InetAddress localHost = (); ("Local IP Address: " + ()); } catch (UnknownHostException e) { (); } } }
2. Use the NetworkInterface class
NetworkInterface
The class provides finer-grained network interface information, which can obtain the IP addresses of all network interfaces.
import ; import ; import ; import ; public class Main { public static void main(String[] args) { try { Enumeration<NetworkInterface> networkInterfaces = (); while (()) { NetworkInterface networkInterface = (); Enumeration<InetAddress> inetAddresses = (); while (()) { InetAddress inetAddress = (); if (!() && ()) { ("Local IP Address: " + ()); } } } } catch (SocketException e) { (); } } }
3. Use third-party libraries (such as Apache Commons Net)
If you need more complex features, you can use third-party libraries such asApache Commons Net
。
import ; import ; import ; public class Main { public static void main(String[] args) { try { InetAddress localHost = (); ("Local IP Address: " + ()); } catch (UnknownHostException e) { (); } } }
How to choose when using it?
-
InetAddress
kind: Simple and easy to use, suitable for most scenarios, especially when you only need to obtain the IP address of the local host. -
NetworkInterface
kind: Suitable for scenarios where you need to obtain the IP addresses of all network interfaces, or you need to filter specific types of IP addresses (such as non-loopback addresses, local addresses, etc.). - Third-party library: Suitable for scenarios that require more complex network operations, such as subnet computing, IP address range processing, etc.
Summarize
For most simple scenarios, use()
It is the easiest and direct way. If you need more granular control or handling multiple network interfaces, you can useNetworkInterface
kind.
This is the end of this article about several common methods for obtaining native IP in Java. For more related Java content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!