获取客户端IP地址
package com.gmk.kpi.common.utils;
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 addr = (InetSocketAddress) getFieldInstance(async,"base#sos#socketWrApper#socket#sc#remoteAddress");
//在Tomcat 8.5以上版本有效
InetSocketAddress addr = (InetSocketAddress) getFieldInstance(async,"base#socketWrapper#socket#sc#remoteAddress");
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 ignore) {
}
}
return null;
}
}
调用方式
@OnOpen
public synchronized void onOpen(Session session) {
this.userService = WsApplicationContextAware.getApplicationContext().getBean(SysUserService.class);
addOnlineCount();
addOnlineUser(session);
InetSocketAddress remoteAddress = WebsocketUtil.getRemoteAddress(session);
log.error("remoteAddress.getAddress().toString() is {}",remoteAddress.getAddress().toString());
}
注意 localhost和ip连接的区别
- 测试时很多是在一台机器上进行,注意发起的wss连接地址如果是localhost或127.0.0.1将返回以下结果,请使用IPV4类型的IP地址
remoteAddress.getAddress().toString() is /0:0:0:0:0:0:0:1