[lnkForumImage]
TotalShareware - Download Free Software

Confronta i prezzi di migliaia di prodotti.
Asp Forum
 Home | Login | Register | Search 


 

Forums >

microsoft.public.dotnet.framework.remoting

Re: How do I check if an address/port is already in use?

Robert Jordan

9/10/2004 6:47:00 PM

Hi,

> Dim chan As Tcp.TcpChannel
> chan = New Tcp.TcpChannel(9213)
> ChannelServices.RegisterChannel(chan)
> RemotingConfiguration.RegisterWellKnownServiceType(GetType(HelloWorld),
> "HelloWorld", WellKnownObjectMode.SingleCall)
>
> This code will normally produce an error if the port 9213 is in use as
> follows:
> An unhandled exception of type 'System.Net.Sockets.SocketException'
> occurred in system.runtime.remoting.dll
> Additional information: Only one usage of each socket address
> (protocol/network address/port) is normally permitted
>
> However I have situation where the port is in use (I used Port Reporter
> from MS to find out which ports were in use) and I don't receive an error.
> This causes remoting to hang.
>
> Is there a simple way to find out every port that is currently in use in
> .Net? So that I can obtain a port that isn't in use and open it for
> exlusiveAddressUse.

you may try this (C#):

try {
int port = FindUnusedPort(IPAdress.Any);
}
catch (SocketException) {
// no free ports
}

....

using System;
using System.Net;
using System.Net.Sockets;

....

public int FindUnusedPort(IPAddress localAddr) {
for (int p = 1024; p <= IPEndPoint.MaxPort; p++) {

Socket s = new Socket(AddressFamily.InterNetwork,
SocketType.Stream,
ProtocolType.Tcp);
try {
s.Bind(new IPEndPoint(localAddr, p));
s.Close();
return p;
}
catch (SocketException ex) {
// EADDRINUSE?
if (ex.ErrorCode == 10048)
continue;
else
throw;
}
}
throw new SocketException(10048);
}

}