如何找到未使用的端口?

发布于 2024-09-13 09:12:16 字数 305 浏览 4 评论 0原文

我需要创建一个脑死亡的 HTTP 服务器,它对 localhost 上的所有内容都返回 404。具体来说,我在验收测试工具下有一个程序,它调用服务器,但为了测试,我想通过跳过不相关的检查来节省时间。

我有一种方法来传递程序用作测试工具一部分的 URL,并且测试工具(当前)仅在端口 80 上创建这样一个服务器。

但是,如果多个测试尝试在该端口运行,则会出现问题同时,因为每个测试工具都尝试在端口 80 上创建 HTTP 服务器,但其中一个测试工具失败。

因此,我想随机化端口并确保它在尝试创建 HTTP 服务器之前可用。如何检查该端口是否正在使用?

I need to create a brain-dead HTTP server that returns 404s for everything on localhost. Specifically, I have a program under an acceptance test harness which calls out to a server, but for testing I want to save time by skipping that unrelated check.

I have a way to pass in the URL the program uses as part of the test harness, and the test harness (currently) just creates such a server on port 80.

However, a problem appears if more than one test attempts to run at the same time, because each test harness tries to create an HTTP server on port 80, which fails for one of the harnesses.

I'd therefore like to randomize the port and ensure it is available before attempting to create the HTTP server. How can I check if that port is in use?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

一刻暧昧 2024-09-20 09:12:16

将套接字绑定到端口 0,系统将选择一个可用端口,在 1024 到 5000 之间,我相信

您稍后可以通过Socket.LocalEndPoint 属性了解分配的端口。

Bind a socket to port 0, the system will pick an available port, between 1024 and 5000 I believe

You can later learn that assigned port with theSocket.LocalEndPoint property.

回眸一笑 2024-09-20 09:12:16

我认为答案是显而易见的:如果套接字侦听失败,则它不可用:选择另一个。只听听例外情况。

I'd have thought the answer is obvious: if a socket listen fails, it's not available: choose another. Just listen to the exceptions.

暖风昔人 2024-09-20 09:12:16

为什么不完全模拟该请求,以便您实际上根本不需要服务器或网络连接?

这将使测试变得不那么脆弱。

好吧,无论如何,您不能在某个预定义范围内生成一个随机端口,然后尝试在其上设置服务器吗?如果已经被占用,则应抛出异常。

Why not mock out the request altogether so that you don't actually need a server or a network connection at all?

That would make for a much less brittle test.

Ok, in any case, could you not just generate a random port in some predefined range, and try to set up a server on it? If it is already occupied, an exception should be thrown.

帅气尐潴 2024-09-20 09:12:16
Socket.Select()

国际研究委员会

Socket.Select()

IIRC

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文