public static async Task<Tuple<int, TimeSpan>> TryToPingServerAsync(string ip, int port, int timeout) {
using (var order = KillerOrder.Create(new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp) {
SendTimeout = timeout,
ReceiveTimeout = timeout
}, timeout)) {
var socket = order.Victim;
var buffer = new byte[3];
try {
var bytes = BitConverter.GetBytes(200);
var endpoint = new IPEndPoint(IPAddress.Parse(ip), port);
await Task.Factory.FromAsync(socket.BeginSendTo(bytes, 0, bytes.Length, SocketFlags.None, endpoint, null, socket),
socket.EndSendTo);
if (order.Killed) return null;
var timer = Stopwatch.StartNew();
var elapsed = TimeSpan.Zero;
var begin = socket.BeginReceive(buffer, 0, buffer.Length, SocketFlags.None, a => { elapsed = timer.Elapsed; }, socket);
if (begin == null) return null;
await Task.Factory.FromAsync(begin, socket.EndReceive);
if (order.Killed) return null;
return buffer[0] != 200 || buffer[1] + buffer[2] <= 0 ? null :
new Tuple<int, TimeSpan>(BitConverter.ToInt16(buffer, 1), elapsed);
} catch (Exception) {
return null;
}
}
}