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 }

 

在服务器上跑代码可以测试

转载于:https://www.cnblogs.com/javallh/p/10687813.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值