feat: get ip from session

This commit is contained in:
godotg
2024-10-06 20:31:10 +08:00
parent 5c8b9c6aad
commit f04838195b
@@ -44,6 +44,28 @@ public abstract class SessionUtils {
return sessionAttr.get();
}
public static String toIp(Session session) {
try {
var remoteAddress = session.getChannel().remoteAddress().toString();
var ip = StringUtils.substringAfterFirst(remoteAddress, StringUtils.SLASH);
ip = StringUtils.substringBeforeFirst(ip, StringUtils.COLON);
return StringUtils.trim(ip);
} catch (Throwable t) {
// do nothing
// to avoid: io.netty.channel.unix.Errors$NativeIoException: readAddress(..) failed: Connection reset by peer
// 有些情况当建立连接过后迅速关闭,这个时候取remoteAddress会有异常
}
return StringUtils.EMPTY;
}
public static long toIpLong(Session session) {
var ip = toIp(session);
if (StringUtils.isBlank(ip)) {
return session.getSid();
}
return NetUtils.ipToLong(ip);
}
public static String sessionInfo(ChannelHandlerContext ctx) {
var session = SessionUtils.getSession(ctx);
if (session == null) {
@@ -56,15 +78,7 @@ public abstract class SessionUtils {
if (session == null) {
return CHANNEL_INFO_TEMPLATE;
}
var remoteAddress = StringUtils.EMPTY;
try {
remoteAddress = StringUtils.substringAfterFirst(session.getChannel().remoteAddress().toString(), StringUtils.SLASH);
} catch (Throwable t) {
// do nothing
// to avoid: io.netty.channel.unix.Errors$NativeIoException: readAddress(..) failed: Connection reset by peer
// 有些情况当建立连接过后迅速关闭,这个时候取remoteAddress会有异常
}
return StringUtils.format(CHANNEL_INFO_TEMPLATE, remoteAddress, session.getSid(), session.getUid());
return StringUtils.format(CHANNEL_INFO_TEMPLATE, toIp(session), session.getSid(), session.getUid());
}
public static String sessionSimpleInfo(ChannelHandlerContext ctx) {