mirror of
https://github.com/tiennm99/zfoo.git
synced 2026-09-03 18:17:17 +00:00
feat: get ip from session
This commit is contained in:
@@ -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) {
|
||||
|
||||
Reference in New Issue
Block a user