Reputation: 6078
I want to listen for HTTP requests and TCP connections on the same port but on different IP addresses.
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.
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.
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).
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.
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.
I am able to run two HttpListeners and two TcpListeners on different IP addresses with the same port, however.
Update
The question was asked:
How do you have assigned two local IP addresses on the same LAN segment?
Originally I had two IP addresses on the same network adapter in the same subnet (255.255.0.0). (See how this is possible at 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.
Upvotes: 2
Views: 2183
Reputation: 6078
Apparently you must tell HTTP.sys which IP addresses to listen on because it hijacks them all by default.
In my case, running the following command allowed me to run HttpListener and TcpListener on the same port on different IP addresses.
netsh http add iplisten 192.168.1.2
Sources
Upvotes: 3