IPUtil工具類,獲取本機、遠程IP的Java代碼

jopen 9年前發布 | 2K 次閱讀 Java daikon,不變量

import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;

import javax.servlet.http.HttpServletRequest;

/**

  • IP工具類
  • @author geeksun
  • 2011-9-23 */ public class IpUtil {

    /**

    • @param 獲取遠程IP
    • @return IP Address */ public static String getIpAddrByRequest(HttpServletRequest request) { String ip = request.getHeader("x-forwarded-for"); if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {

       ip = request.getHeader("Proxy-Client-IP");
      

      } if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {

       ip = request.getHeader("WL-Proxy-Client-IP");
      

      } if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {

       ip = request.getRemoteAddr();
      

      } return ip; }

      /**

    • @return 獲取本機IP
    • @throws SocketException */ public static String getRealIp() throws SocketException { String localip = null;// 本地IP,如果沒有配置外網IP則返回它 String netip = null;// 外網IP

      Enumeration<NetworkInterface> netInterfaces =

       NetworkInterface.getNetworkInterfaces();
      

      InetAddress ip = null; boolean finded = false;// 是否找到外網IP while (netInterfaces.hasMoreElements() && !finded) {

       NetworkInterface ni = netInterfaces.nextElement();
       Enumeration<InetAddress> address = ni.getInetAddresses();
       while (address.hasMoreElements()) {
           ip = address.nextElement();
           if (!ip.isSiteLocalAddress() 
                   && !ip.isLoopbackAddress() 
                   && ip.getHostAddress().indexOf(":") == -1) {// 外網IP
               netip = ip.getHostAddress();
               finded = true;
               break;
           } else if (ip.isSiteLocalAddress() 
                   && !ip.isLoopbackAddress() 
                   && ip.getHostAddress().indexOf(":") == -1) {// 內網IP
               localip = ip.getHostAddress();
           }
       }
      

      }

      if (netip != null && !"".equals(netip)) {

       return netip;
      

      } else {

       return localip;
      

      } }

}</pre>

 本文由用戶 jopen 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!