How do I check if an address/port is already in use?
Messages   Related Types
This message was discovered on microsoft.public.dotnet.framework.remoting.
Responses highlighted in red are from those people who are likely to be able to contribute good, authoratitive information to this discussion. They include Microsoft employees, MVP's and others who IMHO contribute well to these kinds of discussions.
Post a new message to this list...

nichols (VIP)

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.

Thanks
Leslie Nichols

Reply to this message...
 
    
Robert Jordan
Hi,

[Original message clipped]

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);
}

}
Reply to this message...
 
 
System.Net.IPAddress
System.Net.IPEndPoint
System.Net.Sockets.AddressFamily
System.Net.Sockets.ProtocolType
System.Net.Sockets.Socket
System.Net.Sockets.SocketException
System.Net.Sockets.SocketType
System.Runtime.Remoting.Channels.ChannelServices
System.Runtime.Remoting.Channels.Tcp.TcpChannel
System.Runtime.Remoting.RemotingConfiguration
System.Runtime.Remoting.WellKnownObjectMode




Ad
MBR BootFX
Best-of-breed application framework for .NET projects, developed by Matthew Baxter-Reynolds and MBR IT
 
 Copyright © Matthew Baxter-Reynolds 2001-2008. '.NET 247 Software Development Services' is a trading style of MBR IT Solutions Ltd.
Contact Us - Terms of Use - Privacy Policy - www.dotnet247.com