在java中获取tcp连接的开放套接字
我正在用 Java 开发一个 torrent,有一个小问题。如何在 java 中为我的进程获取打开的套接字?我需要按顺序大约有 100 个空闲套接字,就像 10000-10100 一样。我所知道的是,通过使用
socket = new Socket(ip, port);
我们需要提供 ip 和端口。当然,这是调试的情况,我的 IP 是环回的,但我只能通过在端口字段中使用随机数找到一个空闲端口。请告诉我如何找到 tcp 的空闲端口序列。
I'm developing a torrent with Java and there is a small question I have. How can I get an open socket for my process in java? I need about 100 free sockets in a sequence, just like 10000-10100. All I know is that by using
socket = new Socket(ip, port);
We need to provide ip and port. Well of course this is the case of debug and my ip is loopback, but I could find only one free port by using random numbers in port field. Please tell me how to find a sequence of free ports for tcp.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您无法保证自由端口号。您必须扫描机器上的端口,寻找 1024 到 65535 之间的任何可用端口。如果您想创建客户端套接字,您必须尝试按顺序从您想要的每个本地端口进行连接,如果您这样做,则中止并重新启动遇到已使用的端口 - 但当然,如果另一个应用程序也试图获取端口,这种情况可能会继续发生。对于服务器套接字,您必须尝试按顺序绑定到每个端口。
对于客户端套接字,是否需要指定本地端口?如果没有,只需分配您想要的连接数。对于服务器套接字,我会简单地假设我拥有从 10000 到 10100 的所有端口。尽管启动一百台服务器可能不是您想要做的。
对于 Java 中的任何网络,不要使用 Java .net 包,而是使用 Netty ,这更容易与. 一起工作。
You can't guarantee free port numbers. You will have to scan the ports on the machine looking for free ports anywhere between 1024 and 65535. If you want to create a client socket you would have to try and connect from each local port you want in sequence, aborting and starting again if you encounter a used port - but of course this could keep happening if another application is trying to grab ports too. For a server socket, you would have to try and bind to each port in sequence.
For a client socket, do you need to specify the local port? If not, just allocate the number of connections you want. For a server socket, I would simply assume that I owned all ports from, say 10000 to 10100. Although starting a hundred servers probably isn't what you want to do.
With any networking in Java, rather than using the Java .net package, rather use Netty which is much easier to work with.
这可能会带来一些启发;
http://en.wikipedia.org/wiki/List_of_TCP_and_UDP_port_numbers
This might shed some light;
http://en.wikipedia.org/wiki/List_of_TCP_and_UDP_port_numbers
为什么客户端需要一系列端口号?您可以通过 new ServerSocket(0) 获得一个免费的监听端口并询问本地端口。但是,没有充分的理由说明为什么您需要一系列客户端端口号(除了过度热情的出站防火墙规则,网络管理员有时会指定这些规则,但没有意识到没有 API 可以使用它们)。
Why do you need a range of port numbers at the client? You can get a free listening port via new ServerSocket(0) and interrogating the local port. But there's no good reason why you should need a range of client port numbers (other than over-enthusiastic outbound firewall rules, which netadmins sometimes specify without realizing there is no API to use them).