Skip to content

Commit

Permalink
feat: get ip from session
Browse files Browse the repository at this point in the history
  • Loading branch information
jaysunxiao committed Oct 6, 2024
1 parent 5c8b9c6 commit f048381
Showing 1 changed file with 23 additions and 9 deletions.
32 changes: 23 additions & 9 deletions net/src/main/java/com/zfoo/net/util/SessionUtils.java
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,28 @@ public static Session getSession(ChannelHandlerContext ctx) {
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) {
Expand All @@ -56,15 +78,7 @@ public static String sessionInfo(Session session) {
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) {
Expand Down

0 comments on commit f048381

Please sign in to comment.