Необходимо программно проверять доступность сетевых интерфейсов путем удаленного сокет подключения к серверу.
Конфигурация интерфейсов бывает различной (несколько ethernet, wi-fi и модемы) и заранее ее нельзя спрогнозировать.
В функцию передаются IPInterfaceProperties каждого интерфейса.
В процессе работы возникла проблема, gateway существует только для активного на данный момент подключения, т.е.
gateways.Count = 0 для остальных интерфейсов. Поэтому добавить маршрут и проверить соединение не получается.
Может кто сталкивался?
Или подскажет альтернативный путь.
private static bool TestConnection(IPInterfaceProperties properties, IPAddress remoteAddress,int remotePort)
{
bool result = false;
try
{
if (remoteAddress != null)
{
GatewayIPAddressInformationCollection gateways = properties.GatewayAddresses;
UnicastIPAddressInformationCollection addresses = properties.UnicastAddresses;
for (int i = 0; i < addresses.Count; i++)
{
IPAddress addr = addresses[i].Address;
Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
for (int j = 0; j < gateways.Count; j++)
{
GatewayIPAddressInformation gateway = gateways[j];
try
{
// Add the route entry to the route table to solve the Windows XP issue.
AddRoute(gateway.Address.ToString(), remoteAddress.ToString());
// Bind the address to access the remote server.
IPEndPoint local = new IPEndPoint(addr, 0);
socket.Bind(local);
socket.Connect(remoteAddress, remotePort);
result = true;
socket.Disconnect(true);
socket.Shutdown(SocketShutdown.Both);
}
catch
{
result |= false;
}
finally
{
socket.Close();
// Remove the route entry from the route table.
RemoveRoute(remoteAddress.ToString());
}
}
}
}
}
catch (Exception ex)
{
}
return result;
}