c# - 如何在具有相同端口的不同 IP 地址上运行 HttpListener 和 TcpListener?

标签 c# .net

我想在同一端口但不同的 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/

相关文章:

c# - 从 Matlab 到 C# 的多元正态随机数

C# 正则表达式删除 C 风格注释并提取括号之间的文本

.net - 阻止 Visual Studio 自动创建 "Mixed Platforms"解决方案配置

javascript - 使用 .NET 中的 JavaScript 确定 pageLoad() 中是否发生了部分回发以及发生了哪些部分回发

.net - Microsoft.VisualBasic 命名空间 "true .NET"代码是吗?

c# - SQL 索引表连接

c# - 有没有更好的方法来测试这种方法?

c# - DLLImport -> 如何在 C# 中处理 HANDLE

c# - 如何从 WPF 中的第一个窗口打开第二个窗口?

c# - 通过电子邮件发送 log4net 日志作为 System.Net.Mail.Attachment 抛出 IOException(进程锁定)