1. 程式人生 > >c# 搜尋同網段ip

c# 搜尋同網段ip

        /// <summary>
        /// 搜尋同網段ip
        /// </summary>
        /// <param name="ip"></param>
        /// <param name="yanma"></param>
        private void sousuoip(string ip,string yanma)
        {
            //分割字串
            string[] ip_4 = ip.Split('.');
            string[] yanma_4 = yanma.Split('.');
            int[] ip_start = new int[4];
            int[] ip_end = new int[4];
            for (int i = 0;i < 4;i ++ )
            {
                //轉數字
                ip_start[i] = int.Parse(ip_4[i]);
                ip_end[i] = int.Parse(yanma_4[i]);
                //與掩碼與 獲得網段 起始地址
                ip_start[i] = ip_start[i] & ip_end[i];
                //獲得終止地址
                ip_end[i] = 255 - ip_end[i] + ip_start[i];
            }
            //MessageBox.Show(ip_start[0] + "." + ip_start[1] + "." + ip_start[2] + "." + ip_start[3] + "\r\n" +
            //                ip_end[0] + "." + ip_end[1] + "." + ip_end[2] + "." + ip_end[3] + "\r\n");
            //遍歷 ping   只是後16位
            for (int i = ip_start[2]; i <= 255; i++)
            {
                for (int j = ip_start[3]; j <= 255; j++)
                {
                    if (i == ip_end[2] && j == ip_end[3])
                        return;
                    try
                    {
                        myPing = new Ping();
                        myPing.PingCompleted += new PingCompletedEventHandler(_myPing_PingCompleted);

                        string pingIP = ip_start[0].ToString() + "." + ip_start[1].ToString() + "."
                                      + i.ToString() + "." + j.ToString();
                        myPing.SendAsync(pingIP, timeout, null); //const int timeout = 1000; //ping延時
                    }
                    catch { };
                }
            }
        }
        private void _myPing_PingCompleted(object sender, PingCompletedEventArgs e)
        {
            if (e.Reply.Status == IPStatus.Success)
            {
                this.showip.Text += (e.Reply.Address.ToString()+"\r\n");
            }
        }