- Get local IP address of interface used to make a web service call within a Windows service
- IPAddress[] localIPs = Dns.GetHostAddresses(Dns.GetHostName());
- /// <summary>
- /// Returns the IP Address of the given interface
- /// </summary>
- /// <param name="InterfaceName">Name of the interface</param>
- /// <param name="AddressFamily">Address family to search for</param>
- /// <returns>IPAddress of assinged IP address</returns>
- public IPAddress GetIPAddress(string InterfaceName, System.Net.Sockets.AddressFamily AddressFamily)
- {
- System.Net.NetworkInformation.NetworkInterface Interface = GetInterface(InterfaceName);
- if (Interface != null)
- {
- foreach (System.Net.NetworkInformation.UnicastIPAddressInformation IP in Interface.GetIPProperties().UnicastAddresses)
- {
- //Match address family
- if(IP.Address.AddressFamily != AddressFamily)
- continue;
- //Check for IPv6 conditions since we can easily have multiple IPs
- if(IP.Address.AddressFamily == System.Net.Sockets.AddressFamily.InterNetworkV6 && (IP.Address.IsIPv6LinkLocal || IP.AddressPreferredLifetime != uint.MaxValue || IP.AddressValidLifetime != uint.MaxValue))
- continue;
- //We've found the IP
- return IP.Address;
- }
- }
- return null;
- }
- /// <summary>
- /// Returns the Network Interface for the given windows name
- /// </summary>
- /// <param name="InterfaceName">Interface name to get (ie Local Area Connection)</param>
- /// <returns>Network Interface, or null if not found</returns>
- System.Net.NetworkInformation.NetworkInterface GetInterface(string InterfaceName)
- {
- if (InterfaceName == null || InterfaceName.Length == 0)
- return null;
- foreach (System.Net.NetworkInformation.NetworkInterface Interface in NetworkInterfaceArray)
- {
- if (Interface.Name == InterfaceName)
- return Interface;
- }
- return null;
- }
- public static List<string> DisplayDnsAddresses()
- {
- var addresses = NetworkInterface.GetAllNetworkInterfaces()
- .Where(a => a.OperationalStatus == OperationalStatus.Up
- && a.NetworkInterfaceType != NetworkInterfaceType.Loopback)
- .Select(a => a.GetIPProperties())
- .SelectMany(ipp => ipp.UnicastAddresses
- .Select(x => x.Address.ToString()));
- return addresses.ToList();
- }