C#如何自动选择出系统中最合适的IP地址

2019-12-26 13:13:53于丽
  • var interfaceList = NetworkInterface.GetAllNetworkInterfaces();  StringBuilder sb = new StringBuilder(512); 
  • int index = 0;  string message = string.Empty; 
  •   foreach(var item in interfaceList) 
  • {  index++; 
  •   sb.AppendLine(string.Format("Interface{0}: {1}", index, item.Name)); 
  • sb.AppendLine(string.Format("Description: {0}", item.Description));  sb.AppendLine(string.Format("ID: {0}", item.Id)); 
  • sb.AppendLine(string.Format("Type: {0}", item.NetworkInterfaceType));  sb.AppendLine(string.Format("OperationalStatus: {0}", item.OperationalStatus)); 
  • sb.AppendLine(string.Format("IsReceiveOnly: {0}", item.IsReceiveOnly));  sb.AppendLine(string.Format("Speed: {0}", item.Speed)); 
  • sb.AppendLine(string.Format("SupportMulticast: {0}", item.SupportsMulticast));  sb.AppendLine(string.Format("SupportIPV4: {0}", item.Supports(NetworkInterfaceComponent.IPv4))); 
  •   sb.AppendLine(string.Format("IP Properties:")); 
  • var addresses = item.GetIPProperties().UnicastAddresses;  int j = 0; 
  • foreach (var ip in addresses)  { 
  • j++;  sb.AppendLine(string.Format("Address{0}: {1}({2})", j, ip.Address.ToString(),ip.Address.AddressFamily)); 
  • sb.AppendLine(string.Format("IPV4 Mask: {0}", ip.IPv4Mask));  sb.AppendLine(string.Format("PrefixOrigin: {0}", ip.PrefixOrigin)); 
  • sb.AppendLine(string.Format("SuffixOrigin: {0}", ip.SuffixOrigin));  sb.AppendLine(string.Format("DuplicateAddressDetectionState: {0}", ip.DuplicateAddressDetectionState)); 
  • }  sb.AppendLine(); 
  • }   
  • textBox1.Text = sb.ToString();