两个进程如何在 Windows 7 中侦听同一个端口? [英] How are two processes listening to the same port in Windows 7?

查看:31
本文介绍了两个进程如何在 Windows 7 中侦听同一个端口?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 Windows 7 中运行了两个 stunnel 实例,配置为侦听同一个端口,看起来它们都成功侦听了同一个端口(仅使用 socket()/bind()/listen()).两个实例似乎在所有调用中都成功并显示在 netstat 中:

I am running two instances of stunnel in Windows 7, configured to listen to the same port, and it appears that they are both successfully listening on the same port (just using socket()/bind()/listen()). Both instances appear to succeed with all calls and they show up in a netstat:

C:\>netstat -ano | grep 8000
  TCP    0.0.0.0:8000           0.0.0.0:0              LISTENING       5828
  TCP    0.0.0.0:8000           0.0.0.0:0              LISTENING       5852

第一个侦听的接收所有传入请求.

The first one to listen gets all incoming requests.

这与我的所有期望完全相反.(我期待 EADDRINUSE 告诉我端口正忙.)所以....

This is pretty much opposite to all my expectations. (I was expecting to get EADDRINUSE telling me the port was busy.) So....

  1. 为什么/这是如何工作的?这种行为在某些情况下有用吗?
  2. 如果另一个应用程序要捕获传入的请求,我不希望实例成功运行...如何使端口独占?

推荐答案

如果使用标志 SO_REUSEADDR,这在 TCP 套接字应用程序中并不少见.

This can be accomplished if the socket was opened with the flag SO_REUSEADDR, which is not uncommon for TCP socket applications.

通常,SO_REUSEADDR 用于以下两种情况之一:

Typically, SO_REUSEADDR is used for one of two things:

  1. 当进程崩溃、被杀死或强行重启而没有机会关闭其套接字时.或者进程退出了但是套接字(或子连接套接字)仍处于 FIN_WAIT 或 FIN_WAIT2 状态.第二个进程可以打开套接字而不会得到已在使用"错误代码.我读过几篇关于 S.O.表明这是 TCP 套接字的最佳实践.

  1. When a process has crashed, been killed, or forcibly restarted without getting a chance to close its sockets. Or the process exited but the socket (or child connection socket) is still in a FIN_WAIT or FIN_WAIT2 state. The second process can open the socket without getting an "already in use" error code. I've read a couple of posts on S.O. suggesting that this is a best practice for TCP sockets.

同一个服务器程序要么分叉要么同时运行多次.这允许负载平衡,而无需编写服务器程序来使用线程.通常,侦听套接字的程序的另一个实例"将接受传入的连接,而第一个实例正忙于另一个连接.

The same server program either forked or run multiple times concurrently. This allows for load balancing without the server program written to make use of threads. Typically, the "other instance" of the program listening on the socket will accept incoming connections while the first is busy with another connection.

关于您的第二个问题,最简单的方法是不要使用 SO_REUSEADDR.如果您担心可能存在尝试使用 SO_REUSADDR 的流氓应用程序,那么您的应用程序可以使用 SO_EXCLUSIVEADDRUSE.(一个标志,基本上是说,不允许其他应用使用 SO_REUSEADDR 打开同一个端口.)

In regards to your second question, the easiest thing to do is not use SO_REUSEADDR. If you are concerned that there might be a rogue app that does try to use SO_REUSADDR, then your app can use SO_EXCLUSIVEADDRUSE. (A flag, which basically says, "don't allow other apps to open this same port with SO_REUSEADDR.)

这篇关于两个进程如何在 Windows 7 中侦听同一个端口?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆