<返回更多

WebScoket获取客户端IP地址

2022-03-15    Dobbyisfree
加入收藏

获取客户端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连接的区别

remoteAddress.getAddress().toString() is /0:0:0:0:0:0:0:1
声明:本站部分内容来自互联网,如有版权侵犯或其他问题请与我们联系,我们将立即删除或处理。
▍相关推荐
更多资讯 >>>