0

I am looking for the simplest way to block a TCP port in .NET under Windows. I thought the following code would do the job, but it doesn't:

var ipAddress = System.Net.Dns.GetHostEntry("localhost").AddressList[0];
var ipLocalEndpoint = new System.Net.IPEndPoint(ipAddress, port);
var tcpListener = new TcpListener(ipLocalEndpoint);
tcpListener.Start();

I don't understand why that doesn't work. Also, my best idea currently to make it happen is to pop up a server that would serve on the port I want to block. That works, but I'd like an easier solution. Could someone help me out please?

I need to block the provided TCP port in a test suite. I don't want to require admin rights in order to be able to run my tests.

Laurent Michel
  • 1,069
  • 3
  • 14
  • 29
  • 3
    Any reason this isn't a job for the Windows Firewall rather than custom code? – Damien_The_Unbeliever Mar 11 '22 at 09:17
  • You could add a rule directly in the firewall. You should check this answer in another post : https://stackoverflow.com/a/61994862/2417186 – kipy Mar 11 '22 at 09:17
  • I would guess you would need to create a firewall rule that defines the block. – Rand Random Mar 11 '22 at 09:17
  • It is part of an acceptance test suite which I don't want to run as admin. – Laurent Michel Mar 11 '22 at 09:23
  • @LaurentMichel If you cannot accurately simulate production environments (by blocking a port in the Windows Firewall for the duration of the test) then you are not really writing an acceptance-stage test. By definition. [Though another option is to allow non-admin users to edit firewall rules](https://superuser.com/questions/1397509/allow-non-admins-permission-to-manage-windows-firewall) – Dai Mar 11 '22 at 09:29
  • Hmmmm my tests are running on a virtual machine which I can setup as I wish before actually running the tests. I think I will follow your advices and pre-configure the VM in such a way that some TCP ports are blocked. – Laurent Michel Mar 11 '22 at 09:37

0 Answers0