1. 程式人生 > 其它 >Spring boot 如何獲得客戶端 ip 地址以及根據主機名獲得 ip 地址

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();
  }