获取客户端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
声明:本站部分内容及图片来自互联网,转载是出于传递更多信息之目的,内容观点仅代表作者本人,不构成投资建议。投资者据此操作,风险自担。如有任何标注错误或版权侵犯请与我们联系,我们将及时更正、删除。