C#如何判斷同網段電腦是否存在

來源:互聯網
上載者:User

這個問題很簡單

我平時一般是這樣處理的

 

Code
try
               {
                    IPHostEntry myHost = Dns.GetHostByAddress(myIp);
                    HostName = myHost.HostName.ToString();

                }
                catch
                {
                    HostName = "";

                }

 

但是這樣有個問題,新系統使用環境為Vista Vista內建了防火牆 所以再這樣擷取主機的姓名了

於是採取了這樣的方法,調用系統API擷取MAC地址 若存在則確定主機存在:

 

Code
    public class GetMac
    {
        [DllImport("Iphlpapi.dll")]

        private static extern int SendARP(Int32 dest, Int32 host, ref Int64 mac, ref Int32 length);

        [DllImport("Ws2_32.dll")]

        private static extern Int32 inet_addr(string ip);

        public static string GetRemoteMac(string clientIP)
        {

            string ip = clientIP;

            Int32 ldest = inet_addr(ip);

            Int64 macinfo = new Int64();

            Int32 len = 6;

            try
            {

                SendARP(ldest, 0, ref macinfo, ref len);

            }

            catch
            {

                return "";

            }

            string originalMACAddress = Convert.ToString(macinfo, 16);

            if (originalMACAddress.Length < 12)
            {

                originalMACAddress = originalMACAddress.PadLeft(12, '0');

            }

            string macAddress;

            if (originalMACAddress != "0000" && originalMACAddress.Length == 12)
            {

                string mac1, mac2, mac3, mac4, mac5, mac6;

                mac1 = originalMACAddress.Substring(10, 2);

                mac2 = originalMACAddress.Substring(8, 2);

                mac3 = originalMACAddress.Substring(6, 2);

                mac4 = originalMACAddress.Substring(4, 2);

                mac5 = originalMACAddress.Substring(2, 2);

                mac6 = originalMACAddress.Substring(0, 2);

                macAddress = mac1 + "-" + mac2 + "-" + mac3 + "-" + mac4 + "-" + mac5 + "-" + mac6;

            }

            else
            {

                macAddress = "";

            }

            return macAddress.ToUpper();

        } 
    }

 

不知道大家有沒有別的好點的方法呢?

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.