備忘録

備忘録

C#でローカルIPアドレスを列挙する方法

Ⅰ. はじめに

タイトルの通り「C#でローカルIPアドレスを列挙する方法」です。

Ⅱ. サンプルプログラム

Program.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.NetworkInformation;
using System.Net.Sockets;

namespace GetIPAddressesExample
{
  class Program
  {
    static IEnumerable<IPAddress> GetIPAddresses(bool excludeLocalHost = false, bool excludeIPv6 = false)
    {
      var ipaddresses = NetworkInterface
        .GetAllNetworkInterfaces()
        .Where(x => x.OperationalStatus == OperationalStatus.Up)
        .SelectMany(x => x
          .GetIPProperties()
          .UnicastAddresses
          .Select(y => y.Address));

      if (excludeLocalHost)
      {
        ipaddresses = ipaddresses
          .Where(x => !x.Equals(IPAddress.Parse("127.0.0.1")))
          .Where(x => !x.Equals(IPAddress.Parse("::1")));
      }

      if (excludeIPv6)
      {
        ipaddresses = ipaddresses
          .Where(x => x.AddressFamily != AddressFamily.InterNetworkV6);
      }

      return ipaddresses;
    }

    static void Main(string[] args)
    {
      foreach (var x in GetIPAddresses())
      {
        Console.WriteLine(x);
      }

      Console.WriteLine("ローカルホストを省く");
      foreach (var x in GetIPAddresses(excludeLocalHost: true))
      {
        Console.WriteLine(x);
      }

      Console.WriteLine("IPv6を省く");
      foreach (var x in GetIPAddresses(excludeIPv6: true))
      {
        Console.WriteLine(x);
      }
    }
  }
}

Ⅲ. 実行結果

f:id:kagasu:20180115185143p:plain