Not a particularly elegant way, but you can just try opening the host and catching the exceptions AddressAlreadyInUseException. This excludes the use Socketand race conditions that are present in the amazedsaint method: nothing can take the port between the check and your attempt to open the service.
, :
ServiceHost host;
for(int port = 2000; port < 65535; port++) {
var address = GetBaseAddress(port);
host = new ServiceHost(typeof(MyService), address);
try {
host.Open();
break;
}
catch(AddressAlreadyInUseException) {
}
}
GetBaseAddress String.Format, .
, , WCF Discovery .NET 4.