Guest User

Untitled

a guest
May 5th, 2012
33
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.33 KB | None | 0 0
  1. Get local IP address of interface used to make a web service call within a Windows service
  2. IPAddress[] localIPs = Dns.GetHostAddresses(Dns.GetHostName());
  3.  
  4. /// <summary>
  5. /// Returns the IP Address of the given interface
  6. /// </summary>
  7. /// <param name="InterfaceName">Name of the interface</param>
  8. /// <param name="AddressFamily">Address family to search for</param>
  9. /// <returns>IPAddress of assinged IP address</returns>
  10. public IPAddress GetIPAddress(string InterfaceName, System.Net.Sockets.AddressFamily AddressFamily)
  11. {
  12. System.Net.NetworkInformation.NetworkInterface Interface = GetInterface(InterfaceName);
  13. if (Interface != null)
  14. {
  15. foreach (System.Net.NetworkInformation.UnicastIPAddressInformation IP in Interface.GetIPProperties().UnicastAddresses)
  16. {
  17. //Match address family
  18. if(IP.Address.AddressFamily != AddressFamily)
  19. continue;
  20.  
  21. //Check for IPv6 conditions since we can easily have multiple IPs
  22. if(IP.Address.AddressFamily == System.Net.Sockets.AddressFamily.InterNetworkV6 && (IP.Address.IsIPv6LinkLocal || IP.AddressPreferredLifetime != uint.MaxValue || IP.AddressValidLifetime != uint.MaxValue))
  23. continue;
  24.  
  25. //We've found the IP
  26. return IP.Address;
  27. }
  28. }
  29.  
  30. return null;
  31. }
  32.  
  33. /// <summary>
  34. /// Returns the Network Interface for the given windows name
  35. /// </summary>
  36. /// <param name="InterfaceName">Interface name to get (ie Local Area Connection)</param>
  37. /// <returns>Network Interface, or null if not found</returns>
  38. System.Net.NetworkInformation.NetworkInterface GetInterface(string InterfaceName)
  39. {
  40. if (InterfaceName == null || InterfaceName.Length == 0)
  41. return null;
  42.  
  43. foreach (System.Net.NetworkInformation.NetworkInterface Interface in NetworkInterfaceArray)
  44. {
  45. if (Interface.Name == InterfaceName)
  46. return Interface;
  47. }
  48.  
  49. return null;
  50. }
  51.  
  52. public static List<string> DisplayDnsAddresses()
  53. {
  54. var addresses = NetworkInterface.GetAllNetworkInterfaces()
  55. .Where(a => a.OperationalStatus == OperationalStatus.Up
  56. && a.NetworkInterfaceType != NetworkInterfaceType.Loopback)
  57. .Select(a => a.GetIPProperties())
  58. .SelectMany(ipp => ipp.UnicastAddresses
  59. .Select(x => x.Address.ToString()));
  60.  
  61. return addresses.ToList();
  62. }
Advertisement
Add Comment
Please, Sign In to add comment