C# ping网络

 1 using System;
 2 using System.Collections.Generic;
 3 using System.ComponentModel;
 4 using System.Data;
 5 using System.Drawing;
 6 using System.Linq;
 7 using System.Text;
 8 using System.Windows.Forms;
 9 using System.Net.NetworkInformation;
10 
11 namespace pingIp
12 {
13   public partial class Form1 : Form
14   {
15     public Form1()
16     {
17       InitializeComponent();
18     }
19 
20     private void button1_Click(object sender, EventArgs e)
21     {
22 
23       string ip = "192.168.1.16";
24 
25       if (CheckIPAddRight(ip))
26       {
27         Ping pSender = new Ping();
28 
29         PingOptions options = new PingOptions();
30 
31         options.DontFragment = true;
32 
33         byte[] buffer = new byte[512];
34 
35         int timeout = 1000;
36 
37         PingReply reply = pSender.Send(ip, timeout, buffer, options);
38 
39         //如果ping通,返回为Success
40 
41         MessageBox.Show((reply.Status.ToString() == "Success").ToString());
42 
43       }
44     }
45 
46     private bool CheckIPAddRight(string ip)
47     {
48       bool b = false;
49 
50       int intTemp = -1;
51 
52       if (!string.IsNullOrEmpty(ip))
53       {
54         //ip地址不为空
55         string[] ipSplit = ip.Split('.');
56 
57         if (ipSplit.Length == 4)
58         {
59           for (int i = 0; i < ipSplit.Length; i++)
60           {
61             if (int.TryParse(ipSplit[i], out intTemp) && intTemp >= 0 && intTemp <= 255)
62             {
63               //是合法的ip地址
64               b = true;
65             }
66           }
67         }
68       }
69 
70       return b;
71     }
72   }
73 }
posted on 2012-04-25 09:19  孙振营  阅读(341)  评论(0编辑  收藏  举报