Java?獲取本機(jī)IP地址的實(shí)例代碼
前言
在Java中如何準(zhǔn)確的獲取到本機(jī)IP地址呢?網(wǎng)上大部分的做法是InetAddress.getLocalHost().getHostAddress()。這的確能獲取到本機(jī)IP地址,但是是不準(zhǔn)確的。因?yàn)楹雎粤艘粋€(gè)問(wèn)題,網(wǎng)絡(luò)環(huán)境是多變的,一臺(tái)計(jì)算機(jī)不同的網(wǎng)卡有多個(gè)IP地址,Lan、WiFi、藍(lán)牙、熱點(diǎn)、虛擬機(jī)網(wǎng)卡等。
一、規(guī)則
- 127.xxx.xxx.xxx 屬于 “loopback” 地址,即只能你自己的本機(jī)可見(jiàn),就是本機(jī)地址,比較常見(jiàn)的有 127.0.0.1
- 192.168.xxx.xxx 屬于 private 私有地址 (site local address),屬于本地組織內(nèi)部訪問(wèn),只能在本地局域網(wǎng)可見(jiàn)
- 同樣 10.xxx.xxx.xxx、從 172.16.xxx.xxx 到172.31.xxx.xxx 都是私有地址,也是屬于組織內(nèi)部訪問(wèn)
- 169.254.xxx.xxx 屬于連接本地地址(link local IP),在單獨(dú)網(wǎng)段可用
- 從 224.xxx.xxx.xxx 到 239.xxx.xxx.xxx 屬于組播地址
- 比較特殊的 255.255.255.255 屬于廣播地址
- 除此之外的地址就是點(diǎn)對(duì)點(diǎn)的可用的公開(kāi) IPv4 地址
二、獲取
1.使用
public static void main(String[] args) throws SocketException {
System.out.println( IpUtil.getLocalIp4Address().get().toString().replaceAll("/",""));
}2.工具類(lèi)
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;
/**
* 獲取本機(jī)IP 地址
*
* @author dingwen
* 2021.04.28 11:49
*/
public class IpUtil {
/*
* 獲取本機(jī)所有網(wǎng)卡信息 得到所有IP信息
* @return Inet4Address>
*/
public static List<Inet4Address> getLocalIp4AddressFromNetworkInterface() throws SocketException {
List<Inet4Address> addresses = new ArrayList<>(1);
// 所有網(wǎng)絡(luò)接口信息
Enumeration<NetworkInterface> networkInterfaces = NetworkInterface.getNetworkInterfaces();
if (ObjectUtils.isEmpty(networkInterfaces)) {
return addresses;
}
while (networkInterfaces.hasMoreElements()) {
NetworkInterface networkInterface = networkInterfaces.nextElement();
//濾回環(huán)網(wǎng)卡、點(diǎn)對(duì)點(diǎn)網(wǎng)卡、非活動(dòng)網(wǎng)卡、虛擬網(wǎng)卡并要求網(wǎng)卡名字是eth或ens開(kāi)頭
if (!isValidInterface(networkInterface)) {
continue;
}
// 所有網(wǎng)絡(luò)接口的IP地址信息
Enumeration<InetAddress> inetAddresses = networkInterface.getInetAddresses();
while (inetAddresses.hasMoreElements()) {
InetAddress inetAddress = inetAddresses.nextElement();
// 判斷是否是IPv4,并且內(nèi)網(wǎng)地址并過(guò)濾回環(huán)地址.
if (isValidAddress(inetAddress)) {
addresses.add((Inet4Address) inetAddress);
}
}
}
return addresses;
}
/**
* 過(guò)濾回環(huán)網(wǎng)卡、點(diǎn)對(duì)點(diǎn)網(wǎng)卡、非活動(dòng)網(wǎng)卡、虛擬網(wǎng)卡并要求網(wǎng)卡名字是eth或ens開(kāi)頭
*
* @param ni 網(wǎng)卡
* @return 如果滿(mǎn)足要求則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,并且內(nèi)網(wǎng)地址并過(guò)濾回環(huán)地址.
*/
private static boolean isValidAddress(InetAddress address) {
return address instanceof Inet4Address && address.isSiteLocalAddress() && !address.isLoopbackAddress();
}
/*
* 通過(guò)Socket 唯一確定一個(gè)IP
* 當(dāng)有多個(gè)網(wǎng)卡的時(shí)候,使用這種方式一般都可以得到想要的IP。甚至不要求外網(wǎng)地址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));
}
}
參考:
https://www.jianshu.com/p/f619663f0f0a
https://www.cnblogs.com/starcrm/p/7071227.html
下面在分享一段Java獲取本機(jī)IP地址的示例代碼
import java.net.*;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
/**
* 獲取本機(jī)IP 地址
*/
public class IpUtil {
/*
* 獲取本機(jī)所有網(wǎng)卡信息 得到所有IP信息
* @return Inet4Address>
*/
public static List<Inet4Address> getLocalIp4AddressFromNetworkInterface() throws SocketException {
List<Inet4Address> addresses = new ArrayList<>(1);
// 所有網(wǎng)絡(luò)接口信息
Enumeration<NetworkInterface> networkInterfaces = NetworkInterface.getNetworkInterfaces();
if (Objects.isNull(networkInterfaces)) {
return addresses;
}
while (networkInterfaces.hasMoreElements()) {
NetworkInterface networkInterface = networkInterfaces.nextElement();
//濾回環(huán)網(wǎng)卡、點(diǎn)對(duì)點(diǎn)網(wǎng)卡、非活動(dòng)網(wǎng)卡、虛擬網(wǎng)卡并要求網(wǎng)卡名字是eth或ens開(kāi)頭
if (!isValidInterface(networkInterface)) {
continue;
}
// 所有網(wǎng)絡(luò)接口的IP地址信息
Enumeration<InetAddress> inetAddresses = networkInterface.getInetAddresses();
while (inetAddresses.hasMoreElements()) {
InetAddress inetAddress = inetAddresses.nextElement();
// 判斷是否是IPv4,并且內(nèi)網(wǎng)地址并過(guò)濾回環(huán)地址.
if (isValidAddress(inetAddress)) {
addresses.add((Inet4Address) inetAddress);
}
}
}
return addresses;
}
/**
* 過(guò)濾回環(huán)網(wǎng)卡、點(diǎn)對(duì)點(diǎn)網(wǎng)卡、非活動(dòng)網(wǎng)卡、虛擬網(wǎng)卡并要求網(wǎng)卡名字是eth或ens開(kāi)頭
*
* @param ni 網(wǎng)卡
* @return 如果滿(mǎn)足要求則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,并且內(nèi)網(wǎng)地址并過(guò)濾回環(huán)地址.
*/
private static boolean isValidAddress(InetAddress address) {
return address instanceof Inet4Address && address.isSiteLocalAddress() && !address.isLoopbackAddress();
}
/*
* 通過(guò)Socket 唯一確定一個(gè)IP
* 當(dāng)有多個(gè)網(wǎng)卡的時(shí)候,使用這種方式一般都可以得到想要的IP。甚至不要求外網(wǎng)地址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));
}
}到此這篇關(guān)于Java 獲取本機(jī)IP地址的文章就介紹到這了,更多相關(guān)Java 獲取本機(jī)IP地址內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Java http加簽、驗(yàn)簽實(shí)現(xiàn)方案詳解
這篇文章主要介紹了Java http加簽、驗(yàn)簽實(shí)現(xiàn)方案詳解,本文給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2024-07-07
Java對(duì)xls文件進(jìn)行讀寫(xiě)操作示例代碼
Java開(kāi)發(fā)項(xiàng)目中經(jīng)常會(huì)碰到處理Excel文件中數(shù)據(jù)的情況,下面這篇文章主要給大家介紹了利用Java對(duì)xls文件進(jìn)行讀寫(xiě)操作的相關(guān)資料,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面來(lái)一起看看吧。2017-08-08
Springboot中實(shí)現(xiàn)策略模式+工廠模式的方法
這篇文章主要介紹了Springboot中實(shí)現(xiàn)策略模式+工廠模式,具體策略模式和工廠模式的UML我就不給出來(lái)了,使用這個(gè)這兩個(gè)模式主要是防止程序中出現(xiàn)大量的IF ELSE IF ELSE....,接下來(lái)咱們直接實(shí)現(xiàn)Springboot策略模式工廠模式2022-03-03
Java 中HttpURLConnection附件上傳的實(shí)例詳解
這篇文章主要介紹了Java 中HttpURLConnection附件上傳的實(shí)例詳解的相關(guān)資料,希望通過(guò)本文大家能掌握這樣的知識(shí)內(nèi)容,需要的朋友可以參考下2017-09-09
druid配置數(shù)據(jù)庫(kù)連接使用密文密碼方式
這篇文章主要介紹了druid配置數(shù)據(jù)庫(kù)連接使用密文密碼方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,2023-12-12
java基于swing實(shí)現(xiàn)的連連看代碼
這篇文章主要介紹了java基于swing實(shí)現(xiàn)的連連看代碼,包含了游戲中涉及的事件處理與邏輯功能,需要的朋友可以參考下2014-11-11
SpringBoot如何進(jìn)行對(duì)象復(fù)制的實(shí)踐
本文主要介紹了SpringBoot 如何進(jìn)行對(duì)象復(fù)制,文中通過(guò)示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2021-09-09

