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

这一生的挚爱 提交于 2020-08-11 19:18:09

1、获得访问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();
  }
  
String ip = getRemoteIp();

2、获得访问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));
      }
	}
}

3、根据服务器的主机名获得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();
  }

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!