簡體   English   中英

MAC地址和IP地址

[英]MAC Address and IP Address

我有一個C#函數,該函數返回本地IP地址。

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)

功能。

但是我的問題是我不知道如何獲取其他PC 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地址?

每個解決方案將不勝感激。

    // 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)
        {

        }
    }

下面的方法可以在Windows( 在WinXP及更高版本上進行測試 )和Linux與Mono( 在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();
}

查找機器的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();

不,您通常無法獲得已關閉的PC的MAC地址。 這是在數據包中發送的硬件標識符。 您唯一的希望-以及它的一個破解,是檢查本地系統ARP表,例如轉到命令行並鍵入arp -a

但是這對於您想做的事是不可行的。 實際上,即使您知道IP,我相信您所擁有的技術也很薄弱,並且絕對不能在所有遠程情況下(如果有)都可以使用

在同一LAN中查找計算機IP地址的一種方法是開始ping所有可能的IP。 您將一口氣獲得IP和MAC地址……就是從答復中得到的。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM