tags:

views:

253

answers:

3

How do I ensure that a particular port on my computer is not being used for any other purpose other than the service I need in C#??

In my program for a simulation of a lan-messenger, I am getting a connection refused error when trying to connect to a remote host.Hence I need to somehow ensure that the port isn't being used for any other purpose.

+3  A: 

You can't ensure that. Any program can register to listen on any port, and the OS will allow it if no other process is using it.

Your best bet is to choose a port that is now known to be used by any service, and use that as your incoming port. Here's a list of well known ports.

pgb
A: 

Open a tcp-socket listen on it? That blocks anyone else from doing the same.

Connection refused sounds more like a firewall issue.

Marcus Lindblom
+1  A: 
IPAddress localAddr = IPAddress.Parse("127.0.0.1");
server = new TcpListener(localAddr, 0);

This will give you the first available port on local machine.

http://msdn.microsoft.com/en-us/library/system.net.sockets.tcplistener.aspx

bbmud
Don't forget to find out what port it's listening on with...((IPEndPoint)server.LocalEndpoint).Port
Lazarus