- 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 https://www.howtogeek.com/howto/28609/how-can-i-tell-what-is-listening-on-a-tcpip-port-in-windows/ 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
1 Respuesta
0
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;);