C段ping操作(C#入门)

利用周末,造个轮子,学习C#!!

官方examples

查看官方的Ping类,已经很成熟了。以下为官方examples

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
public static void Main (string[] args)
{
Ping pingSender = new Ping ();
PingOptions options = new PingOptions ();
// Use the default Ttl value which is 128,
// but change the fragmentation behavior.
options.DontFragment = true;
// Create a buffer of 32 bytes of data to be transmitted.
string data = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";
byte[] buffer = Encoding.ASCII.GetBytes (data);
int timeout = 120;
PingReply reply = pingSender.Send (args[0], timeout, buffer, options);
if (reply.Status == IPStatus.Success)
{
Console.WriteLine ("Address: {0}", reply.Address.ToString ());
Console.WriteLine ("RoundTrip time: {0}", reply.RoundtripTime);
Console.WriteLine ("Time to live: {0}", reply.Options.Ttl);
Console.WriteLine ("Don't fragment: {0}", reply.Options.DontFragment);
Console.WriteLine ("Buffer size: {0}", reply.Buffer.Length);
}
}

运行结果:

修改

数据显示

官方demo中使用的是默认的Ttl(128),那接下来也使用这个默认值。对demo进行修改,显示所需要的信息即可。

1
2
3
Console.WriteLine ("Address: {0}", reply.Address.ToString ());
Console.WriteLine ("HostName: {0}", Dns.GetHostEntry(reply.Address.ToString()).HostName);
Console.WriteLine ("Time to live: {0}", reply.Options.Ttl);

这只能识别windows系统的,毕竟是128。emmm。

正则匹配IP

使用正则去匹配输入的IP地址是否合理。

1
2
3
4
5
6
// IP地址
Regex regex = new Regex(@"\d+\.\d+\.\d+\.\d+");// (提取IP地址时有用)
// IP地址
Regex regex = new Regex(@"((?:(?:25[0-5]|2[0-4]\\d|[01]?\\d?\\d)\\.){3}(?:25[0-5]|2[0-4]\\d|[01]?\\d?\\d))");
// IP地址
......

调用处理:

效果:

demo

流程:输入–> 判断IP格式(处理)–>遍历(ToString)–>Ping()–>输出–>结束

项目地址:

【参考】

https://msdn.microsoft.com/en-us/library/system.net.networkinformation.ping(v=vs.110).aspx

!坚持技术分享,您的支持将鼓励我继续创作!