static bool tcp_check_do(string host, int port, int timeout) { Sock s = Sock.Connect(host, port, timeout, true, true); try { byte[] d = new byte[1]; d[0] = (byte)'a'; int i; int num = 3; for (i = 0; i < num; i++) { if (s.SendAll(d) == false) { return(false); } if (i <= (num - 1)) { ThreadObj.Sleep(300); } } return(true); } finally { s.Disconnect(); } }
// 実行スレッド void pingerThreadProc(object?param) { string optionsStr = this.DefaultOptions; // まずデフォルトのオプション文字列を読む string hostname = TargetHost; if (hostname._InStri("@")) { if (hostname._GetKeyAndValue(out string hostname2, out string tmp, "@")) { hostname = hostname2; // オプション文字列が個別に指定されていた場合は、それを先に付ける。同じ項目について上書きをすることになる、 optionsStr = tmp._NonNull() + "," + optionsStr; } } // オプション文字列のパース var options = QueryStringList.Parse(optionsStr, splitChar: ',', trimKeyAndValue: true); // IP アドレスバージョンの決定 AllowedIPVersions allowedIPVersions = AllowedIPVersions.All; string ipVerStr = options._GetStrFirst("ipver"); if (ipVerStr._InStr("4") && ipVerStr._InStr("6") == false) { allowedIPVersions = AllowedIPVersions.IPv4; } else if (ipVerStr._InStr("6") && ipVerStr._InStr("4") == false) { allowedIPVersions = AllowedIPVersions.IPv6; } bool preferV6 = false; string ipperfer = options._GetStrFirst("ipprefer"); if (ipperfer._InStri("6")) { preferV6 = true; } IPAddress GetIpAddress(string hostname, AllowedIPVersions allowedIPVersions) { var ip = hostname._ToIPAddress(allowedIPVersions, true); if (ip != null) { return(ip); } return(this.DnsClient.GetIpAddressAsync(hostname, allowedIPVersions, preferV6, noCache: true)._GetResult()); } if (TargetPort == 0) { // ping の実行 try { IPAddress ip = GetIpAddress(hostname, allowedIPVersions); SendPingReply ret = SendPing.Send(ip, null, Timeout); lock (lockObj) { ok = ret.Ok; finished = true; } } catch { lock (lockObj) { ok = false; finished = true; } } Console.Write(ok ? "+" : "-"); } else { int port = TargetPort; bool tcp_check = false; if (port >= 100000) { port -= 100000; tcp_check = true; } // TCP Connect の実行 try { if (tcp_check == false) { IPAddress ip = GetIpAddress(hostname, allowedIPVersions); Sock s = Sock.Connect(ip.ToString(), port, Timeout, true, true); try { if (TcpSendData) { s.SetTimeout(Timeout); long end_tick = Time.Tick64 + (long)Timeout; int num_packets = 0; while (true) { if (Time.Tick64 > end_tick) { break; } if (num_packets >= 16) { break; } byte[] data = new byte[1]; data[0] = (byte)'a'; if (s.SendAll(data) == false) { break; } ThreadObj.Sleep(1); num_packets++; } } s.Disconnect(); } catch { } } else { IPAddress ip = GetIpAddress(hostname, allowedIPVersions); if (tcp_check_do(ip.ToString(), port, Timeout) == false) { throw new ApplicationException(); } } lock (lockObj) { ok = true; finished = true; } } catch { lock (lockObj) { ok = false; finished = true; } } Console.Write(ok ? "*" : "-"); } //EndEvent.Set(); }