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

目录

    • 1、获得访问controller端口的客户端ip地址
    • 2、获得访问endpoint端口的客户端ip地址
    • 3、根据服务器的主机名获得ip地址,并拼接成可以直接访问的链接

1、获得访问controller端口的客户端ip地址

import javax.servlet.http.HttpServletRequest;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

  /**
   * 

* This method helps to get remote ip. *

* * @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;

/**
 * 

* This is static class that provides configuration properties for server endpoint. *

* *

* Thread Safety: This class is immutable and thread safe. *

* * @author * @version 1.0.0 */
public class ServletAwareConfigurator extends Configurator { /** *

* The key for client ip. *

*/
private static final String CLIENT_IP_KEY = "CLIENT_IP"; /** *

* The method helps to get clientIp. *

*/
@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); } /** *

* The method is hacking reflector to expose fields. *

* * @param The instance class * @param 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 {
	 /**
	  * 

* The key for client ip. *

*/
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地址,并拼接成可以直接访问的链接


  /**
   * 

* This method helps to get host address. *

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

你可能感兴趣的:(java,spring,websocket)