Java:如何从 InetAddress 获取连接的端口?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1229655/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-29 15:44:09  来源:igfitidea点击:

Java: How can I get the connected port from an InetAddress?

javasocketsapache-mina

提问by DivideByHero

I'm trying to build a Java NIO-based socket server using Apache Mina. I really need to know the port of the remote host, not just the IP address, and it seems that Mina only exposes a SocketAddress (which can be downcast to InetAddress) object. I can get the IP address from InetAddress, but I normally use Socket.getPort() to get the port number, but Mina appears to obscure these low-level objects. Is there another way? Thanks!

我正在尝试使用 Apache Mina 构建一个基于 Java NIO 的套接字服务器。我真的需要知道远程主机的端口,而不仅仅是IP地址,而且Mina似乎只公开了一个SocketAddress(可以向下转换为InetAddress)对象。我可以从 InetAddress 获取 IP 地址,但我通常使用 Socket.getPort() 来获取端口号,但 Mina 似乎掩盖了这些低级对象。还有其他方法吗?谢谢!

回答by erickson

Downcast the SocketAddressto InetSocketAddress(not InetAddress, which is nota sub-class); this exposes a portaccessor.

向下转换SocketAddressto InetSocketAddress(not InetAddress,它不是一个子类); 这暴露了一个port访问器

回答by ZZ Coder

I have a real old version but this worked for me,

我有一个真正的旧版本,但这对我有用,

public int getPort(SocketAddress address) {
    return ((InetSocketAddress) address).getPort();
}