• Spring boot 如何获得客户端 ip 地址以及根据主机名获得 ip 地址


    获得访问 controller 端口的客户端 ip 地址
    import javax.servlet.http.HttpServletRequest;
    import org.springframework.web.context.request.RequestContextHolder;
    import org.springframework.web.context.request.ServletRequestAttributes;
    
      /**
       * <p>
       * This method helps to get remote ip.
       * </p>
       * 
       * @return The remote ip.
       * @throws RuntimeException If get ip failed.
       */
      public static String getRemoteIp() {
        HttpServletRequest request = null;
        try {
          request =
              ((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes()).getRequest();
        } catch (Exception e) {
          System.out.println("Can not get current IP.");
        }
        return request.getRemoteAddr();
      }
    获得访问 endpoint 端口的客户端 ip 地址
    新建一个配置类,继承 Configurator。
    
    import java.lang.reflect.Field;
    import javax.servlet.http.HttpServletRequest;
    import javax.websocket.HandshakeResponse;
    import javax.websocket.server.HandshakeRequest;
    import javax.websocket.server.ServerEndpointConfig;
    import javax.websocket.server.ServerEndpointConfig.Configurator;
    
    /**
     * <p>
     * This is static class that provides configuration properties for server endpoint.
     * </p>
     *
     * <p>
     * <strong>Thread Safety: </strong> This class is immutable and thread safe.
     * </p>
     * 
     * @author 
     * @version 1.0.0
     */
    public class ServletAwareConfigurator extends Configurator {
    
      /**
       * <p>
       * The key for client ip.
       * </p>
       */
      private static final String CLIENT_IP_KEY = "CLIENT_IP";
    
      /**
       * <p>
       * The method helps to get clientIp.
       * </p>
       */
      @Override
      public void modifyHandshake(ServerEndpointConfig config, HandshakeRequest request,
          HandshakeResponse response) {
        HttpServletRequest httpservletRequest = getField(request, HttpServletRequest.class);
        String clientIP = httpservletRequest.getRemoteAddr();
        config.getUserProperties().put(CLIENT_IP_KEY, clientIP);
      }
    
      /**
       * <p>
       * The method is hacking reflector to expose fields.
       * </p>
       * 
       * @param <I>       The instance class
       * @param <F>       The field type class
       * @param instance  The instance.
       * @param fieldType The type for field.
       * @return The fieldType.
       */
      private static <I, F> F getField(I instance, Class<F> fieldType) {
        try {
          for (Class<?> type = instance.getClass(); type != Object.class; type = type.getSuperclass()) {
            for (Field field : type.getDeclaredFields()) {
              if (fieldType.isAssignableFrom(field.getType())) {
                field.setAccessible(true);
                return (F) field.get(instance);
              }
            }
          }
        } catch (Exception e) {
         System.out.println(
              "Have no access to define the specified class, field, method or constructor.");
        return null;
      }
    }
    在 endpoint 定义处配置 serverEndpoint 为刚才自定义的类。
    
    import javax.websocket.Session;
    import ServletAwareConfigurator;
    
    @ServerEndpoint(value = "/andriod_client", configurator = ServletAwareConfigurator.class)
    @Component
    public class AndriodClientController {
         /**
          * <p>
          * The key for client ip.
          * </p>
          */
         private static final String CLIENT_IP_KEY = "CLIENT_IP";
      
        public String getIp(Session session){
            String clientIp = "N/A";
            if (session.getUserProperties() != null
              && session.getUserProperties().get(CLIENT_IP_KEY) != null) {
            clientIp = String.valueOf(session.getUserProperties().get(CLIENT_IP_KEY));
          }
        }
    }
    根据服务器的主机名获得 ip 地址,并拼接成可以直接访问的链接
    
      /**
       * <p>
       * This method helps to get host address.
       * </p>
       * 
       * @param serverAddress The server address.
       * @param serverApi     The server api.
       * @return The host address.
       * @throws IllegalArgumentException if the argument does not meet requirement.
       * @throws UnknownHostException     if host name is invliad.
       * @throws MalformedURLException    if url is invliad.
       */
      public static String getHostNameAddress(String serverAddress, String serverApi)
          throws UnknownHostException, MalformedURLException {
        ParameterCheckUtility.checkNotNullNorEmptyAfterTrimming(serverAddress, "serverAddress");
        ParameterCheckUtility.checkNotNull(serverApi, "serverApi");
    
        serverAddress = serverAddress.trim();
        StringBuilder url = new StringBuilder();
        URL serverUrl = new URL(serverAddress);
        String protocol = serverUrl.getProtocol();
        String hostName = serverUrl.getHost();
        String hostNameAddress = InetAddress.getByName(hostName).getHostAddress();
        url.append(protocol);
        url.append("://");
        url.append(hostNameAddress);
        int port = serverUrl.getPort();
        if (port != -1) {
          url.append(":");
          url.append(port);
        }
        url.append("/");
        url.append(serverApi.trim());
        return url.toString();
      }
  • 相关阅读:
    php
    图片拖拽
    12.20
    正则详细讲解
    12.19
    正则
    闭包
    date类
    二分查找
    冒泡排序
  • 原文地址:https://www.cnblogs.com/tszr/p/16252384.html
Copyright © 2020-2023  润新知