Java?獲取本機(jī)IP地址的實(shí)例代碼
前言
在Java中如何準(zhǔn)確的獲取到本機(jī)IP地址呢?網(wǎng)上大部分的做法是InetAddress.getLocalHost().getHostAddress()。這的確能獲取到本機(jī)IP地址,但是是不準(zhǔn)確的。因?yàn)楹雎粤艘粋€(gè)問題,網(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ī)可見,就是本機(jī)地址,比較常見的有 127.0.0.1
- 192.168.xxx.xxx 屬于 private 私有地址 (site local address),屬于本地組織內(nèi)部訪問,只能在本地局域網(wǎng)可見
- 同樣 10.xxx.xxx.xxx、從 172.16.xxx.xxx 到172.31.xxx.xxx 都是私有地址,也是屬于組織內(nèi)部訪問
- 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)的可用的公開 IPv4 地址
二、獲取
1.使用
public static void main(String[] args) throws SocketException {
System.out.println( IpUtil.getLocalIp4Address().get().toString().replaceAll("/",""));
}2.工具類
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開頭
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)地址并過濾回環(huán)地址.
if (isValidAddress(inetAddress)) {
addresses.add((Inet4Address) inetAddress);
}
}
}
return addresses;
}
/**
* 過濾回環(huán)網(wǎng)卡、點(diǎn)對(duì)點(diǎn)網(wǎng)卡、非活動(dòng)網(wǎng)卡、虛擬網(wǎng)卡并要求網(wǎng)卡名字是eth或ens開頭
*
* @param ni 網(wǎng)卡
* @return 如果滿足要求則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)地址并過濾回環(huán)地址.
*/
private static boolean isValidAddress(InetAddress address) {
return address instanceof Inet4Address && address.isSiteLocalAddress() && !address.isLoopbackAddress();
}
/*
* 通過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開頭
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)地址并過濾回環(huán)地址.
if (isValidAddress(inetAddress)) {
addresses.add((Inet4Address) inetAddress);
}
}
}
return addresses;
}
/**
* 過濾回環(huán)網(wǎng)卡、點(diǎn)對(duì)點(diǎn)網(wǎng)卡、非活動(dòng)網(wǎng)卡、虛擬網(wǎng)卡并要求網(wǎng)卡名字是eth或ens開頭
*
* @param ni 網(wǎng)卡
* @return 如果滿足要求則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)地址并過濾回環(huán)地址.
*/
private static boolean isValidAddress(InetAddress address) {
return address instanceof Inet4Address && address.isSiteLocalAddress() && !address.isLoopbackAddress();
}
/*
* 通過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日常練習(xí)題,每天進(jìn)步一點(diǎn)點(diǎn)(58)
下面小編就為大家?guī)硪黄狫ava基礎(chǔ)的幾道練習(xí)題(分享)。小編覺得挺不錯(cuò)的,現(xiàn)在就分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧,希望可以幫到你2021-08-08
深入解析Java中的Classloader的運(yùn)行機(jī)制
這篇文章主要介紹了Java中的Classloader的運(yùn)行機(jī)制,包括從JVM方面講解類加載器的委托機(jī)制等,需要的朋友可以參考下2015-11-11
javaweb圖書商城設(shè)計(jì)之分類模塊(2)
這篇文章主要為大家詳細(xì)介紹了javaweb圖書商城設(shè)計(jì)之分類模塊的相關(guān)資料,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2016-11-11
解決RestTemplate 的getForEntity調(diào)用接口亂碼的問題
這篇文章主要介紹了解決RestTemplate 的getForEntity調(diào)用接口亂碼的問題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2021-08-08

