如果是tomcat作为服务器的话,用下面工具类解析客户端IP:
import javax.websocket.RemoteEndpoint;
import javax.websocket.Session;
import java.lang.reflect.Field;
import java.net.InetSocketAddress;
public class WebSocketUtil {
public static InetSocketAddress getRemoteAddress(Session session) {
if (session == null) {
return null;
}
RemoteEndpoint.Async async = session.getAsyncRemote();
//在Tomcat 8.0.x版本有效
InetSocketAddress addr0 = (InetSocketAddress) getFieldInstance(async,"base#sos#socketWrapper#socket#sc#remoteAddress");
System.out.println("clientIP0" + addr0);
//在Tomcat 8.5以上版本有效
InetSocketAddress addr = (InetSocketAddress) getFieldInstance(async, "base#socketWrapper#socket#sc#remoteAddress");
System.out.println("clientIP1" + addr);
return addr;
}
private static Object getFieldInstance(Object obj, String fieldPath) {
String fields[] = fieldPath.split("#");
for (String field : fields) {
obj = getField(obj, obj.getClass(), field);
if (obj == null) {
return null;
}
}
return obj;
}
private static Object getField(Object obj, Class<?> clazz, String fieldName) {
for (; clazz != Object.class; clazz = clazz.getSuperclass()) {
try {
Field field;
field = clazz.getDeclaredField(fieldName);
field.setAccessible(true);
return field.get(obj);
} catch (Exception e) {
}
}
return null;
}
}
如果是undertow作为服务器的话,首先引入Ognl的jar包,用Ognl去解析Async对象然后拿到客户端IP;
<!-- https://mvnrepository.com/artifact/ognl/ognl -->
<dependency>
<groupId>ognl</groupId>
<artifactId>ognl</artifactId>
<version>3.1.10</version>
</dependency>
用下面的工具类即可:
import ognl.DefaultMemberAccess;
import ognl.Ognl;
import ognl.OgnlContext;
import ognl.OgnlException;
import javax.websocket.RemoteEndpoint;
import javax.websocket.Session;
import java.net.InetSocketAddress;
public class WebSocketUtil {
private static OgnlContext context = new OgnlContext();
static
{
// set DefaultMemberAccess with allowed access into the context
context.setMemberAccess(new DefaultMemberAccess(true));
}
public static InetSocketAddress getRemoteAddress(Session session) throws NoSuchFieldException {
if (session == null) {
return null;
}
RemoteEndpoint.Async async = session.getAsyncRemote();
return getRemoteAddress(async);
}
public static InetSocketAddress getRemoteAddress(RemoteEndpoint.Async async)
{
return eval(async, "this$0.undertowSession.webSocketChannel.channel.conduit.socketChannel.remoteAddress");
}
public static InetSocketAddress eval(Object source, String expression)
{
try
{
return(InetSocketAddress) Ognl.getValue(expression, context, source);
}
catch(OgnlException e)
{
throw new IllegalAccessError("expression invalid");
}
}
}
String ip = WebSocketUtil.getRemoteAddress(session).getAddress().toString().substring(1);
这样就可以获得客户端ip了