【问题标题】:MAC Address and IP AddressMAC 地址和 IP 地址
【发布时间】:2011-10-21 04:27:38
【问题描述】:

我有一个返回本地 IP 地址的 C# 函数。

private string GetLocalIPByHostName()
    {
        string host = Dns.GetHostName();
        string LocalIP = string.Empty;
        IPHostEntry ip = Dns.GetHostEntry(host);
        foreach (IPAddress _IPAddress in ip.AddressList)
        {
            if (_IPAddress.AddressFamily.ToString() == "InterNetwork")
            {
                LocalIP = _IPAddress.ToString();

            }
        }
        return LocalIP;
    }

通过使用这个本地 IP 地址,我尝试获取 MAC 地址。

protected string GetMACAddressByIP(string ip)
    {
        try
        {
            ManagementObjectSearcher query= new ManagementObjectSearcher("SELECT * FROM Win32_NetworkAdapterConfiguration");
            ManagementObjectCollection queryCollection = query.Get();
            bool Found = false;
            foreach(ManagementObject _ManagementObject in queryCollection)
            {
                if (_ManagementObject["IPAddress"] != null)
                {
                    string _IPAddress;
                    _IPAddress = string.Join(".", (string[])_ManagementObject["IPAddress"]);

                    if(!_IPAddress.Equals(""))
                    {
                        if(_IPAddress.Equals(ip.Trim()))
                        {
                                Found = true;
                        }
                    }

                    if(Found == true)
                    {
                        if (_ManagementObject["macaddress"] != null)
                        {
                            if (!_ManagementObject["macaddress"].Equals(""))
                            {
                                return (string)_ManagementObject["macaddress"];
                            }
                        }
                    }
                    else
                    {
                        Found = false;
                    }
                }
            }

            MessageBox.Show("No Mac Address Found");
            return "";
        }
        catch(Exception ex)
        {
            MessageBox.Show(ex.Message);
            return "";
        }
    }

其中两个功能正常工作。
但我想做的是在同一 LAN 网络中获取其他 PC 的 IP 地址。
然后,如果我得到这些 IP 地址,那将是我的输入值

GetMACAddressByIP(string ip)

功能。

但我的问题是我不知道如何获取其他电脑的 IP 地址。

private List<string> GetRemoteIPs(string LocalIPAddress)
    {
        List<string> RemoteIPs = new List<string>();

             /*** Here code will be as suggestion of yours.  ****/    

        return RemoteIPs;
    }

那么,下一个问题是
这是否可以获得已经关闭的PC的MAC地址?

每一个解决方案都将不胜感激。

【问题讨论】:

标签: c# sockets networking


【解决方案1】:
    // Get all active IP connections on the network
    private void btnSearch_Click(object sender, EventArgs e)
    {
        System.Net.NetworkInformation.IPGlobalProperties network = System.Net.NetworkInformation.IPGlobalProperties.GetIPGlobalProperties();
        System.Net.NetworkInformation.TcpConnectionInformation[] connections = network.GetActiveTcpConnections();

        foreach (System.Net.NetworkInformation.TcpConnectionInformation connection in connections)
        {

        }
    }

【讨论】:

  • 欢迎来到stackoverflow!最好为示例代码提供简短的描述以提高发布的准确性:)
【解决方案2】:

下面的方法适用于 Windows(在 WinXP 及更高版本上测试)和带有 Mono 的 Linux(在 ubuntu、Suse、Redhat 上测试)。

/// <summary>Get Network Interface Addresses information of current machine.</summary>
/// <returns>Returns Array of Tuple of Mac Address, IP Address, and Status.</returns>
public virtual Tuple<string, IPAddress, OperationalStatus>[] GetNetworkInterfaceAddresses()
{
    List<Tuple<string, IPAddress, OperationalStatus>> list = new List<Tuple<string, IPAddress, OperationalStatus>>();

    NetworkInterfaceType[] acceptedNetInterfaceTypes = new NetworkInterfaceType[]
            {
                NetworkInterfaceType.Ethernet,
                NetworkInterfaceType.Ethernet3Megabit,
                NetworkInterfaceType.FastEthernetFx,
                NetworkInterfaceType.FastEthernetT,
                NetworkInterfaceType.GigabitEthernet,
                NetworkInterfaceType.Wireless80211
            };

    List<NetworkInterface> adapters = NetworkInterface.GetAllNetworkInterfaces()
        .Where(ni => acceptedNetInterfaceTypes.Contains(ni.NetworkInterfaceType)).ToList();

    #region Get the Mac Address

    Func<NetworkInterface, string> getPhysicalAddress = delegate(NetworkInterface am_adapter)
    {
        PhysicalAddress am_physicalAddress = am_adapter.GetPhysicalAddress();
        return String.Join(":", am_physicalAddress.GetAddressBytes()
            .Select(delegate(byte am_v)
            {
                string am_return = am_v.ToString("X");
                if (am_return.Length == 1)
                {
                    am_return = "0" + am_return;
                }

                return am_return;
            }).ToArray());
    };

    #endregion

    #region Get the IP Address

    Func<NetworkInterface, IPAddress> getIPAddress = delegate(NetworkInterface am_adapter)
    {
        IPInterfaceProperties am_ipInterfaceProperties = am_adapter.GetIPProperties();
        UnicastIPAddressInformation am_unicastAddressIP = am_ipInterfaceProperties.UnicastAddresses
            .FirstOrDefault(ua => ua.Address != null && ua.Address.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork);

        if (am_unicastAddressIP == null)
        {
            return null;
        }

        return am_unicastAddressIP.Address;
    };

    #endregion

    // It's possible to have multiple UP Network Interface adapters. So, take the first order from detected Network Interface adapters.
    NetworkInterface firstOrderActiveAdapter = adapters.FirstOrDefault(ni => ni.OperationalStatus == OperationalStatus.Up);

    string macAddress;
    IPAddress ipAddress;

    if (firstOrderActiveAdapter != null)
    {
        macAddress = getPhysicalAddress(firstOrderActiveAdapter);
        ipAddress = getIPAddress(firstOrderActiveAdapter);
        if (ipAddress == null)
        {
            throw new Exception("Unable to get the IP Address v4 from first order of Network Interface adapter of current machine.");
        }

        list.Add(new Tuple<string, IPAddress, OperationalStatus>(macAddress, ipAddress, firstOrderActiveAdapter.OperationalStatus));
        adapters.Remove(firstOrderActiveAdapter);
    }

    foreach (NetworkInterface adapter in adapters)
    {
        macAddress = getPhysicalAddress(adapter);
        ipAddress = getIPAddress(adapter);
        list.Add(new Tuple<string, IPAddress, OperationalStatus>(macAddress, ipAddress, adapter.OperationalStatus));
    }

    if (firstOrderActiveAdapter == null)
    {
        throw new Exception("Unable to get the Active Network Interface of the current machine.");
    }

    return list.ToArray();
}

【讨论】:

    【解决方案3】:

    查找机器ip和mac地址

    cmd > ipconfig/全部

    //Mac地址【以太网适配器以太网:>物理地址】

    var macAddress = NetworkInterface.GetAllNetworkInterfaces();
    var getTarget = macAddress[0].GetPhysicalAddress();
    

    //IP地址[以太网适配器以太网:> IPv4地址]

    string myHostName = Dns.GetHostName();
    IPHostEntry iphostEntries = Dns.GetHostEntry(myHostName);
    IPAddress[] arrIP = iphostEntries.AddressList;
    var getIPAddress = arrIP[arrIP.Length - 1].ToString();
    

    【讨论】:

      【解决方案4】:

      不,您通常无法获取已关闭 PC 的 MAC 地址。这是在数据包中发送的硬件标识符。你唯一的希望——它是一个 hack,是检查本地系统 ARP 表,例如转到命令行并输入 arp -a

      虽然这对于您想要做的事情是不可行的。事实上,即使你知道 IP,我相信你所拥有的技术也是有问题的,而且肯定不会在所有远程情况下都有效(如果有的话)

      【讨论】:

        【解决方案5】:

        在同一 LAN 中查找计算机 IP 地址的一种方法是开始 ping 所有可能的 IP。您将同时获得 IP 和 MAC 地址……从回复的人那里得到。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2013-09-13
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2013-05-09
          • 1970-01-01
          相关资源
          最近更新 更多