Java 獲取本機IP地址的方法的兩種方法
在 Java 編程中,若有本機的 IP 地址的需求,小編來展示一下方法:
一、使用 InetAddress.getLocalHost
一是最基本的獲取本機 IP 地址的方式。
示例代碼:
import java.net.InetAddress;
import java.net.UnknownHostException;
public class GetIPAddress {
public static void main(String[] args) {
try {
InetAddress inetAddress = InetAddress.getLocalHost();
System.out.println("本機 IP 地址: " + inetAddress.getHostAddress());
} catch (UnknownHostException e) {
e.printStackTrace();
}
}
}
這種方法在大多數(shù)簡單場景下可以正常工作,但如果主機有多個網(wǎng)絡接口或者處于復雜的網(wǎng)絡環(huán)境中,可能獲取到的不是期望的 IP 地址。
二、遍歷網(wǎng)絡接口獲取
通過遍歷所有網(wǎng)絡接口來獲取更準確的 IP 地址信息。
示例代碼:
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;
public class GetIPAddressByInterface {
public static void main(String[] args) {
try {
Enumeration<NetworkInterface> networkInterfaces = NetworkInterface.getNetworkInterfaces();
while (networkInterfaces.hasMoreElements()) {
NetworkInterface networkInterface = networkInterfaces.nextElement();
Enumeration<InetAddress> inetAddresses = networkInterface.getInetAddresses();
while (inetAddresses.hasMoreElements()) {
InetAddress inetAddress = inetAddresses.nextElement();
if (!inetAddress.isLoopbackAddress() && inetAddress.getHostAddress().indexOf(':') == -1) {
System.out.println("本機 IP 地址: " + inetAddress.getHostAddress());
}
}
}
} catch (SocketException e) {
e.printStackTrace();
}
}
}
上述代碼首先獲取所有網(wǎng)絡接口,然后遍歷每個接口下的 IP 地址,排除回環(huán)地址(isLoopbackAddress 判斷)和 IPv6 地址(通過 indexOf(‘:’) == -1 判斷),從而得到可能的本機 IP 地址。這種方法在復雜網(wǎng)絡環(huán)境中能獲取到多個符合條件的 IP 地址,可根據(jù)實際需求進一步篩選。
通過以上兩種方法,可以在 Java 程序中獲取本機的 IP 地址,開發(fā)人員可根據(jù)具體的應用場景選擇合適的方法使用。
到此這篇關于Java 獲取本機IP地址的方法的兩種方法的文章就介紹到這了,更多相關Java 獲取本機IP地址內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
Java命令行參數(shù)解析工具jcommander詳解
這篇文章主要為大家介紹了Java命令行參數(shù)解析工具jcommander命令詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2023-09-09
解決spring-cloud-config 多服務共享公共配置的問題
這篇文章主要介紹了解決spring-cloud-config 多服務共享公共配置的問題,本文通過多種方法給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2020-11-11
spring-boot-maven-plugin未指定版本導致的編譯錯誤問題
這篇文章主要介紹了spring-boot-maven-plugin未指定版本導致的編譯錯誤問題,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2023-04-04

