到目前为止,我有以下代码:

NetworkInterface[] adapters = NetworkInterface.GetAllNetworkInterfaces();

foreach (NetworkInterface adapter in adapters)
{
  IPInterfaceProperties properties = adapter.GetIPProperties();

  foreach (IPAddressInformation uniCast in properties.UnicastAddresses)
  {

    // Ignore loop-back addresses & IPv6
    if (!IPAddress.IsLoopback(uniCast.Address) && 
      uniCast.Address.AddressFamily!= AddressFamily.InterNetworkV6)
        Addresses.Add(uniCast.Address);
  }
}

我怎样才能过滤私有IP地址呢?以同样的方式,我过滤环回IP地址.

推荐答案

更详细的回应在这里:

private bool _IsPrivate(string ipAddress)
{
    int[] ipParts = ipAddress.Split(new String[] { "." }, StringSplitOptions.RemoveEmptyEntries)
                             .Select(s => int.Parse(s)).ToArray();
    // in private ip range
    if (ipParts[0] == 10 ||
        (ipParts[0] == 192 && ipParts[1] == 168) ||
        (ipParts[0] == 172 && (ipParts[1] >= 16 && ipParts[1] <= 31))) {
        return true;
    }

    // IP Address is probably public.
    // This doesn't catch some VPN ranges like OpenVPN and Hamachi.
    return false;
}

Asp.net相关问答推荐

此版本的 SQL Server 不支持用户实例登录标志.连接将关闭

Server.Transfer 在执行子请求时抛出错误.如何解决?

MSCharts找不到请求类型'GET'的http处理程序错误

如何使用 javascript 获取 MVC 应用程序的基本 URL

即使使用正确的 Accepts 标头,WebAPI 也不会返回 XML

区分开发、登台和生产环境之间的 web.config

Twitter bootstrap glyphicons 不会出现在发布模式 404 中

为什么对 ASP.NET MVC 控制器的调用不执行 DelegatingHandler?

无法使用单例Microsoft.AspNetCore.Hosting.Internal.HostedServiceExecutor中的范围服务MyDbContext

ASP.NET 中的多选下拉列表

Eval()、XPath() 和 Bind() 等数据绑定方法只能在数据绑定控件的上下文中使用

Page.IsValid 是如何工作的?

如何避免 ASP.NET MVC 中的 HttpRequestValidationException 呈现导致异常的相同视图

如何将数据集转换为数据表

HttpContext.Current.Request.Url.Host 它返回什么?

如何强制 netwtonsoft json 序列化程序将 datetime 属性序列化为字符串?

将列表转换为 json 格式 - 快速简便的方法

获取 POST 变量

System.Web.Caching 还是 System.Runtime.Caching 更适合 .NET 4 Web 应用程序

ASP.NET 网格视图与列表视图