IPUtils.java 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. package com.loan.system.utils.logUtils;
  2. import javax.servlet.http.HttpServletRequest;
  3. import java.net.*;
  4. import java.util.Enumeration;
  5. /*
  6. * ip工具类
  7. *
  8. * @author chen
  9. * @date 2019/10/01
  10. * */
  11. public class IPUtils {
  12. public static String getLocalIP() throws SocketException {
  13. String localIP = null;
  14. Enumeration allNetInterfaces = NetworkInterface.getNetworkInterfaces();
  15. InetAddress ip = null;
  16. while (allNetInterfaces.hasMoreElements()) {
  17. NetworkInterface netInterface = (NetworkInterface) allNetInterfaces.nextElement();
  18. Enumeration addresses = netInterface.getInetAddresses();
  19. while (addresses.hasMoreElements()) {
  20. ip = (InetAddress) addresses.nextElement();
  21. if (ip != null && ip instanceof Inet4Address) {
  22. localIP = ip.getHostAddress();
  23. if (!"127.0.0.1".equalsIgnoreCase(localIP)) {
  24. return localIP;
  25. }
  26. }
  27. }
  28. }
  29. return localIP;
  30. }
  31. /**
  32. * 获取当前网络ip
  33. *
  34. * @param request
  35. * @return
  36. */
  37. public static String getIpAddr(HttpServletRequest request) {
  38. String ipAddress = request.getHeader("x-forwarded-for");
  39. if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
  40. ipAddress = request.getHeader("Proxy-Client-IP");
  41. }
  42. if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
  43. ipAddress = request.getHeader("WL-Proxy-Client-IP");
  44. }
  45. if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
  46. ipAddress = request.getRemoteAddr();
  47. if (ipAddress.equals("127.0.0.1") || ipAddress.equals("0:0:0:0:0:0:0:1")) {
  48. //根据网卡取本机配置的IP
  49. InetAddress inet = null;
  50. try {
  51. inet = InetAddress.getLocalHost();
  52. } catch (UnknownHostException e) {
  53. e.printStackTrace();
  54. }
  55. ipAddress = inet.getHostAddress();
  56. }
  57. }
  58. //对于通过多个代理的情况,第一个IP为客户端真实IP,多个IP按照','分割
  59. if (ipAddress != null && ipAddress.length() > 15) { //"***.***.***.***".length() = 15
  60. if (ipAddress.indexOf(",") > 0) {
  61. ipAddress = ipAddress.substring(0, ipAddress.indexOf(","));
  62. }
  63. }
  64. return ipAddress;
  65. }
  66. }