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

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

  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值