[英]How can you run an HttpListener and TcpListener on different IP addresses with the same port?
I want to listen for HTTP requests and TCP connections on the same port but on different IP addresses.我想在同一个端口上但在不同的 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);
If I start the HttpListener first, I get an error when starting the TcpListener.如果我先启动 HttpListener,启动 TcpListener 时会出错。
An attempt was made to access a socket in a way forbidden by its access permissions
试图以访问权限禁止的方式访问套接字
If I start the TcpListener first, I get an error when starting the HttpListener.如果我先启动 TcpListener,启动 HttpListener 时会出错。
The process cannot access the file because it is being used by another process
该进程无法访问该文件,因为它正被另一个进程使用
When the HttpListener is running, netstat reveals that it's only listening on the IP address specified, but it's running in the System process (PID 4).当 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
When the TcpListener is running, it's also only listening on the IP address specified, but it's running in my application's process.当 TcpListener 运行时,它也只侦听指定的 IP 地址,但它在我的应用程序进程中运行。
Proto Local Address Foreign Address State PID
TCP 192.168.1.3:40000 0.0.0.0:0 LISTENING 18316
Even though they listen on different IP addresses, there's still a conflict that won't let me do both at the same time.即使他们侦听不同的 IP 地址,仍然存在冲突,无法让我同时进行这两项操作。
I am able to run two HttpListeners and two TcpListeners on different IP addresses with the same port, however.但是,我可以在具有相同端口的不同 IP 地址上运行两个 HttpListener 和两个 TcpListener。
Update更新
The question was asked:被问到的问题是:
How do you have assigned two local IP addresses on the same LAN segment?
您如何在同一 LAN 网段上分配两个本地 IP 地址?
Originally I had two IP addresses on the same network adapter in the same subnet (255.255.0.0).最初我在同一个子网 (255.255.0.0) 的同一个网络适配器上有两个 IP 地址。 (See how this is possible at https://superuser.com/questions/571575/connect-to-two-lan-networks-with-a-single-card ).
(在https://superuser.com/questions/571575/connect-to-two-lan-networks-with-a-single-card 上了解这是如何实现的)。
To rule out this as an issue, I setup a virtual machine with two network adapters on different subnets.为了排除这个问题,我在不同的子网上设置了一个带有两个网络适配器的虚拟机。 The results were the same.
结果是一样的。
Apparently you must tell HTTP.sys which IP addresses to listen on because it hijacks them all by default.显然,您必须告诉 HTTP.sys 侦听哪些 IP 地址,因为默认情况下它会劫持所有 IP 地址。
In my case, running the following command allowed me to run HttpListener and TcpListener on the same port on different IP addresses.就我而言,运行以下命令允许我在不同 IP 地址的同一端口上运行 HttpListener 和 TcpListener。
netsh http add iplisten 192.168.1.2
Sources来源
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.