tbf/TestBenchFramework/BenchControl/Network/Adapter/AdapterInfo.cs

209 lines
6.5 KiB
C#

using System;
using System.Collections.Generic;
using System.Net;
using System.Net.NetworkInformation;
using System.Text;
using System.Web;
namespace TBF.BenchControl.Network.Adapter
{
/// <summary>
/// Class for the storing information about a network adapter.
/// </summary>
public class AdapterInfo
{
public string Description; /// Description of the network adapter.
public IPAddress IPAddress; /// IP address of the network adapter.
public IPAddress NetMask; /// Mask of the network adapter.
/// Constructor
public AdapterInfo(string description)
{
Description = description;
}
public IPAddress GetBroadcastAddress()
{
byte[] ipAdressBytes = IPAddress.GetAddressBytes();
byte[] subnetMaskBytes = NetMask.GetAddressBytes();
if (ipAdressBytes.Length != subnetMaskBytes.Length)
throw new ArgumentException("Lengths of IP address and subnet mask do not match.");
byte[] broadcastAddress = new byte[ipAdressBytes.Length];
for (int i = 0; i < broadcastAddress.Length; i++)
{
broadcastAddress[i] = (byte)(ipAdressBytes[i] | (subnetMaskBytes[i] ^ 255));
}
return new IPAddress(broadcastAddress);
}
///------------------------------------------------------
/// Static members and functions
///------------------------------------------------------
/// <summary>
/// Private list of the available network adapters.
/// </summary>
static List<AdapterInfo> netAdapters;
/// <summary>
/// Retrieves the list of network adapters.
/// Never returns 'null', calls RefreshNetAdaptersInfo() the first time it is used.
/// If you want to refresh the list of the network adapters later, explicitly call
/// the RefreshNetAdaptersInfo() method.
/// </summary>
public static List<AdapterInfo> NetAdapters
{
get
{
if (netAdapters == null) RefreshNetAdaptersInfo();
return netAdapters;
}
}
/// <summary>
/// Refreshes the information about network adapters stored in the netAdapters list.
/// </summary>
public static void RefreshNetAdaptersInfo()
{
if (netAdapters == null) netAdapters = new List<AdapterInfo>();
else netAdapters.Clear();
NetworkInterface[] nics = NetworkInterface.GetAllNetworkInterfaces();
foreach (NetworkInterface adapter in nics)
{
AdapterInfo info = new AdapterInfo(adapter.Description);
netAdapters.Add(info);
IPInterfaceProperties properties = adapter.GetIPProperties();
if (properties == null)
continue;
UnicastIPAddressInformationCollection uniCast = properties.UnicastAddresses;
if (uniCast == null)
continue;
foreach (UnicastIPAddressInformation uni in uniCast)
{
if (info == null)
{
info = new AdapterInfo(adapter.Description);
netAdapters.Add(info);
}
info.IPAddress = uni.Address;
if (uni.IPv4Mask != null) info.NetMask = uni.IPv4Mask;
info = null;
}
}
}
/// <summary>
/// Gets the loopback network adapter.
/// </summary>
public static AdapterInfo LoopbackAdapter
{
get
{
List<AdapterInfo> adapters = NetAdapters;
foreach (AdapterInfo a in adapters)
{
if (a.IPAddress != null && a.IPAddress.Equals(IPAddress.Loopback)) return a;
}
return null;
}
}
/// <summary>
/// Gets the default network adapter - the first one which his not a loopback adapter.
/// Network adapters with IP address have preference, adapters without IP address
/// (like an unconnected wireless adapter) are used just when there is no adapter with IP.
///
/// Default adapter is used when none was specified in the configuration file
/// and it is used to initialize Options-General dialog-tab.
/// </summary>
public static AdapterInfo DefaultAdapter
{
get
{
List<AdapterInfo> adapters = NetAdapters; /// Make a copy to avoid interference
AdapterInfo adapterWithoutIP = null; /// Use this one if there is no other better adapter
foreach (AdapterInfo a in adapters)
{
if (!a.IPAddress.Equals(IPAddress.Loopback))
{
if (a.IPAddress != null) return a;
else if (adapterWithoutIP == null) adapterWithoutIP = a;
}
}
return adapterWithoutIP == null ? LoopbackAdapter : adapterWithoutIP;
}
}
/// <summary>
/// Get network adapter info from the description string.
/// </summary>
/// <param name="description">Description</param>
/// <returns>AdapterInfo object reference</returns>
public static AdapterInfo GetNetAdapter(string description)
{
List<AdapterInfo> adapters = NetAdapters;
foreach (AdapterInfo a in adapters)
{
if (a.Description != description ||
a.IPAddress == null ||
a.IPAddress.AddressFamily == System.Net.Sockets.AddressFamily.InterNetworkV6 ||
a.IPAddress.Equals(IPAddress.Loopback) ||
a.NetMask == null)
{
continue;
}
return a;
}
return DefaultAdapter;
}
/// <summary>
/// Encodes the given string as URL parameter.
/// </summary>
/// <param name="pathToEncode">String to be encoded.</param>
/// <returns>String encoded as the URL parameter.</returns>
public static string UrlPathEncode(string pathToEncode)
{
StringBuilder sb = new StringBuilder(pathToEncode.Length * 3);
sb.Append(pathToEncode);
// % must be first!!!
sb.Replace("%", "%" + Convert.ToInt32('%').ToString("X2"));
// ?, & and / are not convertable by HttpUtility.UrlPathEncode
sb.Replace("?", "%" + Convert.ToInt32('?').ToString("X2"));
sb.Replace("&", "%" + Convert.ToInt32('&').ToString("X2"));
sb.Replace("/", "%" + Convert.ToInt32('/').ToString("X2"));
// Additional chars. E.g.: # didn't work in the path passed to the Uri class. "c:\\sour#ce\\my # proj".
sb.Replace("#", "%" + Convert.ToInt32('#').ToString("X2"));
// Backslash must be removed because it is not accepted by Uri class when passing path into it. E.g.: "C:%5Csource" is not acceptable.
//sb.Replace("\\", "%" + Convert.ToInt32('\\').ToString("X2"));
//// I removed following chars because I do not know if it is good idea to replace them (see previous line with '\\' char).
sb.Replace("\r", "%" + Convert.ToInt32('\r').ToString("X2"));
sb.Replace("\n", "%" + Convert.ToInt32('\n').ToString("X2"));
sb.Replace("\t", "%" + Convert.ToInt32('\t').ToString("X2"));
string s = sb.ToString();
s = HttpUtility.UrlPathEncode(s);
//sb.Length = 0;
//sb.Append(HttpUtility.UrlPathEncode(s));
//for (int i = 0; i < sb.Length; i += 3)
//{
// char c = sb[i];
// if (c == '%')
// continue;
// sb[i] = '%';
// sb.Insert(i + 1, Convert.ToUInt64(c).ToString("X2"));
//}
return s;
}
}
}