简体   繁体   English

如何在.NET C#中以编程方式确定IP是否来自同一LAN

[英]How to determine whether an IP is from the same LAN programatically in .NET C#

I know that if an IP falls outside the Subnet Mask + Local IP rules, it will be only reachable through an Gateway. 我知道如果IP超出子网掩码+本地IP规则,它只能通过网关访问。 The problem is that I don't know how to obtain the local IP address, neither the local subnet mask, programatically using .NET. 问题是我不知道如何使用.NET以编程方式获取本地IP地址,也不知道本地子网掩码。 Any of you can help me? 你们中的任何人可以帮助我吗?

I will use this information to squeeze the maximum performance from my batch SQL insertion queue. 我将使用此信息从我的批处理SQL插入队列中挤出最大性能。 If the SQL server falls in the same subnet, then it will use an algorithm optimized for mininum latency, otherwise I´ll use one optimized for high latency. 如果SQL服务器属于同一子网,那么它将使用针对最小延迟优化的算法,否则我将使用针对高延迟优化的算法。

You can use the classes inside the System.Net.NetworkInformation namespace (introduced in .NET 2.0): 您可以使用System.Net.NetworkInformation命名空间(在.NET 2.0中引入)中的类:

        NetworkInterface[] interfaces = NetworkInterface.GetAllNetworkInterfaces();

        foreach (NetworkInterface iface in interfaces)
        {
            IPInterfaceProperties properties = iface.GetIPProperties();

            foreach (UnicastIPAddressInformation address in properties.UnicastAddresses)
            {
                Console.WriteLine(
                    "{0} (Mask: {1})",
                    address.Address,
                    address.IPv4Mask
                    );
            }
        }

There is an alternative way using the NetworkInformation class: 使用NetworkInformation类还有另一种方法:

public static void ShowNetworkInterfaces()
{
    // IPGlobalProperties computerProperties = IPGlobalProperties.GetIPGlobalProperties();
    NetworkInterface[] nics = NetworkInterface.GetAllNetworkInterfaces();

    if (nics == null || nics.Length < 1)
    {
        Console.WriteLine("  No network interfaces found.");
        return;
    }

    Console.WriteLine("  Number of interfaces .................... : {0}", nics.Length);
    foreach (NetworkInterface adapter in nics)
    {
        IPInterfaceProperties properties = adapter.GetIPProperties();
        Console.WriteLine();
        Console.WriteLine(adapter.Description);
        Console.WriteLine(String.Empty.PadLeft(adapter.Description.Length,'='));
        Console.WriteLine("  Interface type .......................... : {0}", adapter.NetworkInterfaceType);
        Console.WriteLine("  Physical Address ........................ : {0}", adapter.GetPhysicalAddress().ToString());
        string versions ="";

        // Create a display string for the supported IP versions.
        if (adapter.Supports(NetworkInterfaceComponent.IPv4))
        {
            versions = "IPv4";
        }
        if (adapter.Supports(NetworkInterfaceComponent.IPv6))
        {
            if (versions.Length > 0)
            {
                versions += " ";
            }
            versions += "IPv6";
        }
        Console.WriteLine("  IP version .............................. : {0}", versions);
        UnicastIPAddressInformationCollection uniCast = properties.UnicastAddresses;
        if (uniCast != null)
        {
            foreach (UnicastIPAddressInformation uni in uniCast)
            {
                Console.WriteLine("  Unicast Address ......................... : {0}", uni.Address);
                Console.WriteLine("     Subnet Mask  ......................... : {0}", uni.IPv4Mask);
            }
        }
    Console.WriteLine();
    }
}

The code sample is a mashup form the examples provided by Msdn, simplified to only show the information you probably need. 代码示例是mashup形式,由Msdn提供的示例,简化为仅显示您可能需要的信息。

EDIT: Took me too long (too many things at the same time :) ) to make this post, and Mitch beat me to it :) 编辑:花了太长时间(太多的东西同时:) :)发表这篇文章,米奇打败了我:)

This will get you the host name and the IP address. 这将获取主机名和IP地址。 I'm assuming you know the IPs in your LAN so you should be able to determine if the IP address is outside the LAN that way: 我假设您知道局域网中的IP,因此您应该能够确定IP地址是否在局域网之外:

// Get the host name of local machine.
strHostName = Dns.GetHostName();
Console.WriteLine("Local Machine's Host Name: " + strHostName);

// Using the host name, get the IP address list.
IPHostEntry ipEntry = Dns.GetHostEntry(strHostName);
IPAddress[] addr = ipEntry.AddressList;

for (int i = 0; i < addr.Length; i++)
{
     Console.WriteLine("IP Address {0}: {1} ", i, addr[i].ToString());
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM