プロが教えるわが家の防犯対策術!

現在C#で、IPアドレスの取得で苦戦しています。
例えばNICが2枚ささっている状態で、
特定の通信先と通信を行っているNICのIPアドレスを取得するには
どうすればいいでしょうか。

最終的には、通信を行っているIPアドレスから、
どちらのNICで通信を行っているか判別して
そのNICのMACアドレスを取得したいです。

現在考えているのは、pingを通信先に飛ばしてその送信元のIPアドレスを取得するという事です。

ただ、これも実現方法がいまいち曖昧で、現在取得できていません・・・。

Pingを飛ばすところまではできているのですが、送信元のIPアドレスの取得のやり方がわかりません。

通信先は固定の予定なので、その通信先と通信する際に使用しているIPアドレスを知りたいです。

pingの送信元のIPアドレスを取得する方法、
またはほかに良い方法があれば教えていただけますでしょうか。

よろしくお願いします。

A 回答 (2件)

TCP での接続が確立しているなら、以下のコードで確認できます。


※全角文字でインデントしてあります。

// filename: get_mac.cs
// compile: %WINDIR%\Microsoft.NET\Framework\v3.5\csc get_mac.cs
// or
// %WINDIR%\Microsoft.NET\Framework\v2.0.50727\csc get_mac.cs

using System;
using System.Net;
using System.Net.NetworkInformation;

namespace get_mac
{
  class Program
  {
    static void Main(string[] args)
    {
      if(args.Length == 2)
      {
        print_mac(args[0], Convert.ToInt32(args[1]));
      }
      else
      {
        Console.WriteLine("Usage: get_mac <remore IP address> <remote port>");
      }
    }

    private static void print_mac(string remote_ip, int port)
    {
      string ip = get_local_ip_address(remote_ip, port);
      if(ip != "")
      {
        string mac = get_mac_address(ip);
        if(mac != "")
        {
          Console.WriteLine("MAC address: " + mac);
        }
      }
      else
      {
          Console.WriteLine("Not found");
      }
    }

    private static string get_local_ip_address(string remote_ip, int port)
    {
      IPGlobalProperties ipProperties = IPGlobalProperties.GetIPGlobalProperties();
      IPEndPoint[] endPoints = ipProperties.GetActiveTcpListeners();
      TcpConnectionInformation[] tcpConnections = ipProperties.GetActiveTcpConnections();
      foreach (TcpConnectionInformation tcp_info in tcpConnections)
      {
        if (tcp_info.RemoteEndPoint.Address.ToString() == remote_ip &&
         tcp_info.State == TcpState.Established &&
         tcp_info.RemoteEndPoint.Port == port
        )
        {
          return tcp_info.LocalEndPoint.Address.ToString();
        }
      }
      return "";
    }

    private static string get_mac_address(string ip)
    {
      NetworkInterface[] adapters = NetworkInterface.GetAllNetworkInterfaces();
    
      foreach (NetworkInterface adapter in adapters)
      {
        if (adapter.OperationalStatus == OperationalStatus.Up)
        {
          IPInterfaceProperties ip_prop = adapter.GetIPProperties();
          UnicastIPAddressInformationCollection addrs = ip_prop.UnicastAddresses;
          foreach (UnicastIPAddressInformation addr in addrs)
          {
            if (addr.Address.ToString() == ip)
            {
              PhysicalAddress phy = adapter.GetPhysicalAddress();
              return phy.ToString();
            }
          }
        }
      }
      return "";
    }
  }
}
    • good
    • 0

ルーティングテーブルを取得してなんかできないかなぁ.

    • good
    • 0

お探しのQ&Aが見つからない時は、教えて!gooで質問しましょう!