Java WebSocket获取客户端IP

如果是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了

评论 7
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

抓了只蛙

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值