using System; using System.Collections.Generic; using System.Linq; using System.Net.NetworkInformation; using System.Text; using System.Text.RegularExpressions; using System.Threading.Tasks; namespace FileSend { internal class Helper { /// /// 匹配IP地址是否合法 /// /// 当前需要匹配的IP地址 /// true:表示合法 public static bool MatchIP(string ip) { bool success = false; if (!string.IsNullOrEmpty(ip)) { //判断是否为IP success = Regex.IsMatch(ip, @"^((2[0-4]\d|25[0-5]|[01]?\d\d?)\.){3}(2[0-4]\d|25[0-5]|[01]?\d\d?)$"); } return success; } /// /// 匹配端口是否合法 /// /// /// true:表示合法 public static bool MatchPort(int port) { bool success = false; if (port >= 0 && port <= 65535) { success = true; } return success; } /// /// 检查IP是否可ping通 /// /// 要检查的IP /// 是否可连通【true:表示可以连通】 public static bool CheckIPIsPing(string strIP) { if (!string.IsNullOrEmpty(strIP)) { if (!MatchIP(strIP)) { return false; } // Windows L2TP VPN和非Windows VPN使用ping VPN服务端的方式获取是否可以连通 Ping pingSender = new Ping(); PingOptions options = new PingOptions(); // 使用默认的128位值 options.DontFragment = true; //创建一个32字节的缓存数据发送进行ping string data = "testtesttesttesttesttesttesttest"; byte[] buffer = Encoding.ASCII.GetBytes(data); int timeout = 120; PingReply reply = pingSender.Send(strIP, timeout, buffer, options); return (reply.Status == IPStatus.Success); } else { return false; } } /// /// 连续几次查看是否某个IP可以PING通 /// /// ping的IP地址 /// 每次间隔时间,单位:毫秒 /// 测试次数 /// 是否可以连通【true:表示可以连通】 public static bool MutiCheckIPIsPing(string strIP, int waitMilliSecond, int testNumber) { for (int i = 0; i < testNumber - 1; i++) { if (CheckIPIsPing(strIP)) { return true; } Thread.Sleep(waitMilliSecond); } return CheckIPIsPing(strIP); } } }