How to detect a network port is open for communication ? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
- 1

How to detect a network port is open for communication ?

I want to know if a certain port on the network / pc is available for communication. With the help of this link I used netstat -ab to confirm that the program is connected to the defined port. Is the a similar command to prove that the program can use that port for communication. Either in command prompt or via a c# object

25th Oct 2017, 8:15 PM
sneeze - avatar
1 Answer
You can just open the Resources Manager app (it should be called like that in English), go to network and check the available ports from there. Then, keep in mind that when you create a Socket object in C#, you're not forced to bind it to a port, as a free one (usually from 50000 onwards) is automatically assigned to it. You can get it using it's LocalEndPoint property. For example: // Omitting params for brevity Socket sock = new Socket(...); // Writing the local port that has been // automatically assigned to the socket Console.Write( sock.LocalEndPoint.Port); If you are using other objects different from Socket, like TcpClient or TcpListener, you can find in almost all cases the underlying socket used for the connection as a property. For example: TcpClient client = new TcpClient(); // The client property is the socket used // by the TcpClient class. // If you are using a TcpListener, it // would be Server Console.Write( client.Client.LocalEndPoint.Port;);
24th Apr 2018, 7:22 PM
Mante - avatar