java獲取真實的IP地址工具類


在實際項目中,有調用微信支付完成支付功能,在微信支付的請求參數中需要傳遞一個本機的ip地址,java代碼運行環境目前為windows10以及centos7.

以下為獲取ip地址工具類:

 1 package com.dq.schooldomain.utils;
 2 
 3 import java.net.InetAddress;
 4 import java.net.NetworkInterface;
 5 import java.net.UnknownHostException;
 6 import java.util.Enumeration;
 7 /**
 8  * @Author Allen.Lv
 9  * @Description //TODO 
10  * @Date 9:50 2019/4/11
11  * @Desc: Coding Happy!
12  **/
13 public class IpAddress {
14     public static InetAddress getLocalHostLANAddress() throws UnknownHostException {
15         try {
16             InetAddress candidateAddress = null;
17             // 遍歷所有的網絡接口
18             for (Enumeration ifaces = NetworkInterface.getNetworkInterfaces(); ifaces.hasMoreElements();) {
19                 NetworkInterface iface = (NetworkInterface) ifaces.nextElement();
20                 // 在所有的接口下再遍歷IP
21                 for (Enumeration inetAddrs = iface.getInetAddresses(); inetAddrs.hasMoreElements();) {
22                     InetAddress inetAddr = (InetAddress) inetAddrs.nextElement();
23                     if (!inetAddr.isLoopbackAddress()) {// 排除loopback類型地址
24                         if (inetAddr.isSiteLocalAddress()) {
25                             // 如果是site-local地址,就是它了
26                             return inetAddr;
27                         } else if (candidateAddress == null) {
28                             // site-local類型的地址未被發現,先記錄候選地址
29                             candidateAddress = inetAddr;
30                         }
31                     }
32                 }
33             }
34             if (candidateAddress != null) {
35                 return candidateAddress;
36             }
37             // 如果沒有發現 non-loopback地址.只能用最次選的方案
38             InetAddress jdkSuppliedAddress = InetAddress.getLocalHost();
39             if (jdkSuppliedAddress == null) {
40                 throw new UnknownHostException("The JDK InetAddress.getLocalHost() method unexpectedly returned null.");
41             }
42             return jdkSuppliedAddress;
43         } catch (Exception e) {
44             UnknownHostException unknownHostException = new UnknownHostException(
45                     "Failed to determine LAN address: " + e);
46             unknownHostException.initCause(e);
47             throw unknownHostException;
48         }
49     }
50 }

 

在服務器上跑代碼可以測試


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM