我想在同一端口但不同的 IP 地址上监听 HTTP 请求和 TCP 连接。
string prefix = "http://192.168.1.2:40000/";
HttpListener http = new HttpListener();
http.Prefixes.Add(prefix);
IPEndPoint ep = new IPEndPoint(IPAddress.Parse("192.168.1.3"), 40000);
TcpListener tcp = new TcpListener(ep);
如果我先启动 HttpListener,则启动 TcpListener 时会出现错误。
An attempt was made to access a socket in a way forbidden by its access permissions
如果我先启动 TcpListener,启动 HttpListener 时会出现错误。
The process cannot access the file because it is being used by another process
当 HttpListener 运行时,netstat 显示它仅监听指定的 IP 地址,但它在系统进程 (PID 4) 中运行。
Proto Local Address Foreign Address State PID
TCP 192.168.1.2:40000 0.0.0.0:0 LISTENING 4
当 TcpListener 运行时,它也仅监听指定的 IP 地址,但它在我的应用程序进程中运行。
Proto Local Address Foreign Address State PID
TCP 192.168.1.3:40000 0.0.0.0:0 LISTENING 18316
即使它们监听不同的 IP 地址,仍然存在冲突,无法让我同时执行这两个操作。
但是,我可以在具有相同端口的不同 IP 地址上运行两个 HttpListener 和两个 TcpListener。
更新
提出的问题:
How do you have assigned two local IP addresses on the same LAN segment?
最初,我在同一子网 (255.255.0.0) 的同一网络适配器上有两个 IP 地址。 (查看 https://superuser.com/questions/571575/connect-to-two-lan-networks-with-a-single-card 了解这是如何实现的)。
为了排除这个问题,我在不同的子网上设置了一个具有两个网络适配器的虚拟机。结果是一样的。
最佳答案
显然,您必须告诉 HTTP.sys 要监听哪些 IP 地址,因为默认情况下它会劫持所有这些 IP 地址。
就我而言,运行以下命令允许我在不同 IP 地址的同一端口上运行 HttpListener 和 TcpListener。
netsh http add iplisten 192.168.1.2
来源
关于c# - 如何在具有相同端口的不同 IP 地址上运行 HttpListener 和 TcpListener?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32672493/