Java獲取本機IP的幾種常見方法
在Java中獲取本地IP地址有多種方式,以下是幾種常見的方法:
1. 使用 InetAddress 類
InetAddress 類是Java標準庫中用于表示IP地址的類,可以通過它獲取本地主機的IP地址。
import java.net.InetAddress;
import java.net.UnknownHostException;
public class Main {
public static void main(String[] args) {
try {
InetAddress localHost = InetAddress.getLocalHost();
System.out.println("Local IP Address: " + localHost.getHostAddress());
} catch (UnknownHostException e) {
e.printStackTrace();
}
}
}
2. 使用 NetworkInterface 類
NetworkInterface 類提供了更細粒度的網(wǎng)絡接口信息,可以獲取所有網(wǎng)絡接口的IP地址。
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;
public class Main {
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.isSiteLocalAddress()) {
System.out.println("Local IP Address: " + inetAddress.getHostAddress());
}
}
}
} catch (SocketException e) {
e.printStackTrace();
}
}
}
3. 使用第三方庫(如 Apache Commons Net)
如果你需要更復雜的功能,可以使用第三方庫,如 Apache Commons Net。
import org.apache.commons.net.util.SubnetUtils;
import java.net.InetAddress;
import java.net.UnknownHostException;
public class Main {
public static void main(String[] args) {
try {
InetAddress localHost = InetAddress.getLocalHost();
System.out.println("Local IP Address: " + localHost.getHostAddress());
} catch (UnknownHostException e) {
e.printStackTrace();
}
}
}
使用時如何選擇?
InetAddress類:簡單易用,適合大多數(shù)場景,尤其是只需要獲取本地主機的IP地址時。NetworkInterface類:適合需要獲取所有網(wǎng)絡接口的IP地址,或者需要過濾特定類型的IP地址(如非回環(huán)地址、本地地址等)的場景。- 第三方庫:適合需要更復雜網(wǎng)絡操作的場景,如子網(wǎng)計算、IP地址范圍處理等。
總結
對于大多數(shù)簡單場景,使用 InetAddress.getLocalHost() 是最簡單和直接的方式。如果你需要更細粒度的控制或處理多個網(wǎng)絡接口,可以使用 NetworkInterface 類。
到此這篇關于Java獲取本機IP的幾種常見方法的文章就介紹到這了,更多相關Java獲取本機IP內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
FreeMarker如何調(diào)用Java靜態(tài)方法及靜態(tài)變量方法
這篇文章主要介紹了FreeMarker如何調(diào)用Java靜態(tài)方法及靜態(tài)變量方法,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2023-12-12
springboot實現(xiàn)https雙向傳輸協(xié)議的示例代碼
本文主要介紹了springboot實現(xiàn)https雙向傳輸協(xié)議的示例代碼,包含配置證書和私鑰路徑、調(diào)用請求方法等步驟,具有一定的參考價值,感興趣的可以了解一下2025-03-03
Springboot如何使用Aspectj實現(xiàn)AOP面向切面編程
這篇文章主要介紹了Springboot如何使用Aspectj實現(xiàn)AOP面向切面編程,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-01-01
springboot構造樹形結構數(shù)據(jù)并查詢的方法
本文主要介紹了springboot怎樣構造樹形結構數(shù)據(jù)并查詢,文中通過示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下2021-11-11

