获取用于在Windows服务中进行web服务调用的接口的本地IP地址

本文关键字:服务 接口 地址 IP 调用 用于 Windows 获取 web | 更新日期: 2023-09-27 18:21:20

我们正在开发一个安装在客户端系统上的Windows服务。该应用程序定期调用我们服务器上的SOAP web服务。我们希望在每次SOAP请求到达我们的服务时将客户端系统的本地IP地址包括在请求中,以进行故障排除。通过查看这里的其他帖子,我发现了以下代码来获得系统上接口的IP列表:

IPAddress[] localIPs = Dns.GetHostAddresses(Dns.GetHostName());

此代码包含在Windows服务中。有没有一种简单的方法可以确定此阵列中的哪个IP被分配给路由web服务调用的接口?

获取用于在Windows服务中进行web服务调用的接口的本地IP地址

如果您使用的是WCF 3.5或更高版本,您可以使用消息属性直接在服务中获取客户端的IP地址,如本博客中的代码所示

您可以在Windows服务中运行以下代码来获取盒子上任何接口的IP。

/// <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;
}

返回一个列表,该列表包含在运行它的机器上的IP,只要适配器在运行,而不是环回接口。

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();
}

这可能需要改进一下。我不知道如何确定网络服务将使用哪个接口,但如果你知道必须使用哪个网关才能访问你的网络,也许你可以确定它。