zoukankan      html  css  js  c++  java
  • 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 }

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

  • 相关阅读:
    Flink批处理读取Hive写入MySql
    数组与链表的优缺点
    Flink任务暂停重启
    Flink优化总结
    Flink集群监控
    flink连接器-流处理-读写redis
    Flink连接器-批处理-读写Hbase
    flink on yarn
    java的常量定界符
    特殊注释的使用
  • 原文地址:https://www.cnblogs.com/javallh/p/10687813.html
Copyright © 2011-2022 走看看