-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathPingSender.cs
73 lines (61 loc) · 1.91 KB
/
PingSender.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.NetworkInformation;
using System.Text;
using System.Threading.Tasks;
namespace PingGraf
{
public class PingSender
{
private Struct data = new Struct();
private string _who;
private int _timeout;
public PingSender(string who, int timeout = 1000)
{
this._who = who;
this._timeout = timeout;
}
public async Task<PingResponse> SendPing()
{
IPAddress ip = null;
if (!System.Net.IPAddress.TryParse(_who, out ip)) return new PingResponse();
Ping pingSender = new Ping();
string data = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";
byte[] buffer = Encoding.ASCII.GetBytes(data);
PingOptions options = new PingOptions(64,true);
try
{
PingReply rep = await pingSender.SendPingAsync(_who, _timeout, buffer, options);
return new PingResponse() { Status = 1, Reply=rep };
}
catch (Exception ex)
{
MessageBox.Show(ex.Message,"ping error");
return new PingResponse();
}
}
private void PingCompleteCallback(object sender, PingCompletedEventArgs e)
{
if (e.Cancelled)
{
//ping cancel
((AutoResetEvent)e.UserState).Set();
}
if (e.Error != null)
{
//ping failed
((AutoResetEvent)e.UserState).Set();
}
PingReply rep = e.Reply;
Console.WriteLine(rep.RoundtripTime.ToString());
((AutoResetEvent)e.UserState).Set();
}
}
public class PingResponse
{
public int Status { get; set; } = 0;
public PingReply Reply { get; set; }
}
}