public IPingReply Send(string host, int timeout, byte[] buffer, PingOptions options) { PingReply pingReply = this._ping.Send(host, timeout, buffer, options); return(this._mapper.Map <PingReply, IPingReply>(pingReply)); }
static void Main(string[] args) { IntPtr handle = GetConsoleWindow(); ShowWindow(handle, SW_HIDE); try { ConfigPath.ReadArgs(args, typeof(string)); AppToStart.ReadArgs(args, typeof(string)); AppArgs.ReadArgs(args, typeof(string)); AppToCheck.ReadArgs(args, typeof(string)); Delay.ReadArgs(args, typeof(int)); LogsOn.ReadArgs(args, typeof(bool)); VpnPath.ReadArgs(args, typeof(string)); VpnArgs.ReadArgs(args, typeof(string)); CheckConnection.ReadArgs(args, typeof(string)); StartDelay.ReadArgs(args, typeof(int)); } catch (Exception e) { ShowWindow(handle, SW_SHOW); Log.L("Read arguments error!", ConsoleColor.Red); Log.L(e.ToString(), ConsoleColor.Red); Console.ReadLine(); return; } if (Convert.ToBoolean(LogsOn.Value) == true) { ShowWindow(handle, SW_SHOW); } //Loading config try { Config config = new Config((string)ConfigPath.Value, true); if (config.ConfigLoadedSuccessful) { if (config.Values.ContainsKey(AppToStart.Argument)) { AppToStart.Value = config.GetValue <object>(AppToStart.Argument); } if (config.Values.ContainsKey(AppArgs.Argument)) { AppArgs.Value = config.GetValue <object>(AppArgs.Argument); } if (config.Values.ContainsKey(AppToCheck.Argument)) { AppToCheck.Value = config.GetValue <object>(AppToCheck.Argument); } if (config.Values.ContainsKey(Delay.Argument)) { Delay.Value = config.GetValue <object>(Delay.Argument); } if (config.Values.ContainsKey(LogsOn.Argument)) { LogsOn.Value = config.GetValue <object>(LogsOn.Argument); } if (config.Values.ContainsKey(VpnPath.Argument)) { VpnPath.Value = config.GetValue <object>(VpnPath.Argument); } if (config.Values.ContainsKey(VpnArgs.Argument)) { VpnArgs.Value = config.GetValue <object>(VpnArgs.Argument); } if (config.Values.ContainsKey(CheckConnection.Argument)) { CheckConnection.Value = config.GetValue <object>(CheckConnection.Argument); } if (config.Values.ContainsKey(StartDelay.Argument)) { StartDelay.Value = config.GetValue <object>(StartDelay.Argument); } } } catch (Exception e) { Log.L("Config error!\r\n" + e.ToString()); } //App set requred if ((string)AppToStart.Value == "") { ShowWindow(handle, SW_SHOW); Log.L(HelpMessage.Help, ConsoleColor.White); Console.ReadLine(); return; } //Check connection before connecting VPN bool needVPN = true; if ((string)CheckConnection.Value != "") { Ping ping = new Ping(); try { PingReply pingReply = ping.Send((string)CheckConnection.Value); if (pingReply.Status == IPStatus.Success) { needVPN = false; } } catch { } } //Start VPN if it has and if it needs bool vpnStarted = false; if ((string)VpnPath.Value != "" && needVPN) { if (System.IO.File.Exists((string)VpnPath.Value)) { try { System.Diagnostics.Process.Start((string)VpnPath.Value, (string)VpnArgs.Value); vpnStarted = true; } catch (Exception e) { ShowWindow(handle, SW_SHOW); Log.L("VPN error!", ConsoleColor.Red); Log.L(e.ToString(), ConsoleColor.Red); Console.ReadLine(); return; } } } //Check connection if ((string)CheckConnection.Value != "" && needVPN && vpnStarted) { Ping ping = new Ping(); bool success = false; while (!success) { try { PingReply pingReply = ping.Send((string)CheckConnection.Value); if (pingReply.Status == IPStatus.Success) { success = true; } Console.WriteLine(pingReply.Status); } catch { } if (!success) { Thread.Sleep(1000); } } } //AutoStart AutoStart autoStart; try { autoStart = new AutoStart((string)AppToStart.Value, (string)AppArgs.Value, Convert.ToInt32(Delay.Value), (string)AppToCheck.Value); } catch (Exception e) { ShowWindow(handle, SW_SHOW); Log.L("Autostart error!", ConsoleColor.Red); Log.L(e.ToString(), ConsoleColor.Red); Console.ReadLine(); return; } if (Convert.ToInt32(StartDelay.Value) > 0) { try { Thread.Sleep(Convert.ToInt32(StartDelay.Value)); } catch (Exception e) { Log.L(e.ToString(), ConsoleColor.Red); falseCount++; } } while (true) { try { autoStart.StartAuto(); } catch (Exception e) { Log.L(e.ToString(), ConsoleColor.Red); if (falseCount >= falseLimit) { return; } } try { Thread.Sleep(Convert.ToInt32(Delay.Value)); } catch (Exception e) { Log.L(e.ToString(), ConsoleColor.Red); falseCount++; if (falseCount >= falseLimit) { return; } } } }
private void timer1_Tick(object sender, EventArgs e) { ip = null; reply = null; error = false; rtts = null; rtt = null; try { ip = new IPAddress(134744072); reply = p.Send(ip); rtts = (float)((float)reply.RoundtripTime / (float)1000f); rtt = reply.RoundtripTime; notifyIcon1.Text = "QNetMon - " + rtt.ToString() + " ms"; } catch (Exception) { error = true; } Bitmap showing = icons[(int)color.white]; if (rtt != null && ip != null && reply != null && error == false) { if (rtt < 100) { showing = icons[(int)color.green]; } else if (rtt < 200) { showing = icons[(int)color.violet]; } else if (rtt < 300) { showing = icons[(int)color.yellow]; } else if (rtt < 500) { showing = icons[(int)color.pink]; } else if (rtt < 1500) { showing = icons[(int)color.red]; } else if (rtt < 1500) { showing = icons[(int)color.gray]; } else { showing = icons[(int)color.black]; } } else { //remains default - white } IntPtr icoPtr = showing.GetHicon(); // Get an Hicon for myBitmap. Icon ico = Icon.FromHandle(icoPtr); // Create a new icon from the handle. notifyIcon1.Icon = ico; }
private void ThreadReceivingAnnSetup() { receivingAnnouncement = new Thread(() => { //Creates a UdpClient for reading incoming data. UdpClient receivingUdpClient = new UdpClient(port); receivingUdpClient.JoinMulticastGroup(IPAddress.Parse("224.0.0.2")); //Creates an IPEndPoint to record the IP Address and port number of the sender. // The IPEndPoint will allow you to read datagrams sent from any source. IPEndPoint RemoteIpEndPoint = new IPEndPoint(IPAddress.Any, port); receivingUdpClient.EnableBroadcast = true; receivingUdpClient.Client.SetIPProtectionLevel(IPProtectionLevel.Unrestricted); //receivingUdpClient.MulticastLoopback = false; try { while (true) { int i = 0; byte[] name1 = null; byte[] image = null; int length = 0; // Blocks until a message returns on this socket from a remote host. Byte[] receiveBytes = receivingUdpClient.Receive(ref RemoteIpEndPoint); string ipforSearch = RemoteIpEndPoint.Address.ToString(); length = BitConverter.ToInt32(receiveBytes, i); if (ipforSearch.Equals(IPAddress.Loopback.ToString())) { ipforSearch = App.app.broadcastCalculation().ToString(); } bool found = false; if (ipforSearch.Equals(IPAddress.Loopback.ToString())) { length = 0; } IPAddress myIp = App.app.broadcastCalculation(); foreach (IPAddress ip in App.app.myIp) { if (ip.Equals(RemoteIpEndPoint.Address)) { found = true; } } if (!Properties.Settings.Default.DiscoverySelf && found) { length = 0; } //if (!myIp.Equals(IPAddress.Parse(ipforSearch)) && found) length=0; if (length == 0) { Ping pingSender = new Ping(); IPAddress address = RemoteIpEndPoint.Address; PingReply reply = pingSender.Send(address); bool b = true; if (reply.Status == IPStatus.Success) { b = true; } else { b = false; } Dispatcher.Invoke(new Action(() => { List <Person> tmp = PersonOne.ToList(); foreach (Person p in tmp) { if (p.IP.Equals(ipforSearch)) { if (!p.tick || !b) { foreach (ToSend o in send_list.ToList()) { if (o.ip.Equals(ipforSearch)) { insertDeleteSendList(o, false); } } PersonOne.Remove(p); } else { foreach (ToSend o in send_list.ToList()) { if (o.ip.Equals(ipforSearch)) { if (o.bkgWorker == null) { insertDeleteSendList(o, false); PersonOne.Remove(p); break; } o.o = PersonOne; o.index = p; } } } } } })); continue; } i += 4; name1 = new byte[length]; for (int j = 0; j < length; j++) { name1[j] = receiveBytes[i + j]; } i += length; length = BitConverter.ToInt32(receiveBytes, i); // MemoryStream stream = receiveImage(RemoteIpEndPoint.Address); person = searchIp(ipforSearch); if (person != null) { if (person.tick) { continue; } } if (person == null || person.change != length) { image = receiveImage(RemoteIpEndPoint.Address); Dispatcher.Invoke(System.Windows.Threading.DispatcherPriority.Send, new Action(() => { if (person != null) { int index = PersonOne.IndexOf(person); bool tick = person.tick; PersonOne.RemoveAt(index); person = new Person(); person.Name = Encoding.ASCII.GetString(name1); person.IP = RemoteIpEndPoint.Address.ToString(); person.Image = ByteArraytoBitmap(image);//StreamtoBitmap(stream);// new BitmapImage( person.change = length; person.tick = tick; PersonOne.Insert(index, person); return; } person = new Person(); person.Name = Encoding.ASCII.GetString(name1); person.change = length; person.tick = false; person.IP = RemoteIpEndPoint.Address.ToString(); person.Image = ByteArraytoBitmap(image);//StreamtoBitmap(stream);// new BitmapImage(Uri); PersonOne.Add(person); })); } else { if (Encoding.ASCII.GetString(name1).Equals(person.Name)) { continue; } Dispatcher.Invoke(System.Windows.Threading.DispatcherPriority.Send, new Action(() => { int index = PersonOne.IndexOf(person); PersonOne.RemoveAt(index); person.Name = Encoding.ASCII.GetString(name1); PersonOne.Insert(index, person); })); } } } catch (Exception) { } finally { receivingUdpClient.Close(); } }); }
/* * Registers an agent with the coordinator, or updates the ping time * * Returns true if a restart is required */ public static PingResponse Ping(AgentInfo UpdatedInfo) { AgentsDirty = true; // Add a known set of configuration items UpdatedInfo.Configuration["LastPingTime"] = DateTime.UtcNow; // Retreive information the agent can provide for us and supply defaults if (!UpdatedInfo.Configuration.ContainsKey("GroupName")) { UpdatedInfo.Configuration["GroupName"] = "Default"; } // If the Agent is working for someone, replace the local user name with // the user name on the machine that it's working for if (UpdatedInfo.Configuration.ContainsKey("WorkingFor")) { // Look up the other user name string BossAgentName = UpdatedInfo.Configuration["WorkingFor"] as string; if ((Agents.ContainsKey(BossAgentName)) && (Agents[BossAgentName].Configuration.ContainsKey("UserName"))) { UpdatedInfo.Configuration["UserName"] = Agents[BossAgentName].Configuration["UserName"]; } } else { UpdatedInfo.Configuration["WorkingFor"] = ""; } if (!UpdatedInfo.Configuration.ContainsKey("AssignedTo")) { UpdatedInfo.Configuration["AssignedTo"] = ""; UpdatedInfo.Configuration["AssignedTime"] = DateTime.UtcNow; } if (!UpdatedInfo.Configuration.ContainsKey("UserName")) { UpdatedInfo.Configuration["UserName"] = "******"; } // If the agent is remote, ping the machine to make sure we can talk to it // but only if the Agent didn't provide an IP address for us if (!UpdatedInfo.Configuration.ContainsKey("IPAddress")) { // By default, we'll set the IP address to the loopback value UpdatedInfo.Configuration["IPAddress"] = IPAddress.Loopback; bool IPAddressUpdateSuccess = false; if (UpdatedInfo.Name != Environment.MachineName) { try { // Use the name, which can fail if DNS isn't enabled or if there's no host file Ping PingSender = new Ping(); PingReply Reply = PingSender.Send(UpdatedInfo.Name); if (Reply.Status == IPStatus.Success) { // With a success, update the known IP address for this agent UpdatedInfo.Configuration["IPAddress"] = Reply.Address; IPAddressUpdateSuccess = true; } } catch (Exception) { // Any exception is a total failure } } // With a failure, update the agent's state to prevent usage if (!IPAddressUpdateSuccess) { UpdatedInfo.State = AgentState.Blocked; } } PingResponse Response; lock ( Agents ) { if (!Agents.ContainsKey(UpdatedInfo.Name)) { // If this is a new agent, tell it to restart itself to pick up the latest version Response = PingResponse.Restart; } else if (Agents[UpdatedInfo.Name].State == AgentState.Restarting) { Response = PingResponse.Restart; // If this agent has been instructed to restart, keep overriding the // state until it's freed up to actually restart if (UpdatedInfo.State == AgentState.Available) { UpdatedInfo.State = AgentState.Restarted; } else { // Keep us in this cycle on the next ping UpdatedInfo.State = AgentState.Restarting; } } else { Response = PingResponse.Success; AgentInfo PreviousInfo = Agents[UpdatedInfo.Name]; // If the WorkingFor changed, update the time string PreviousWorkingFor = PreviousInfo.Configuration["WorkingFor"] as string; string UpdatedWorkingFor = UpdatedInfo.Configuration["WorkingFor"] as string; DateTime UpdatedWorkingTime = DateTime.MaxValue; if (UpdatedWorkingFor != PreviousWorkingFor) { UpdatedWorkingTime = DateTime.UtcNow; } else if (PreviousInfo.Configuration.ContainsKey("WorkingTime")) { UpdatedWorkingTime = ( DateTime )PreviousInfo.Configuration["WorkingTime"]; } UpdatedInfo.Configuration["WorkingTime"] = UpdatedWorkingTime; // Based on whether or not the agent is Working currently, update some state if (UpdatedInfo.State != AgentState.Working) { // No other agent should be AssignedTo it foreach (AgentInfo Agent in Agents.Values) { if ((Agent.Configuration["AssignedTo"] as string) == UpdatedInfo.Name) { Agent.Configuration["AssignedTo"] = ""; Agent.Configuration["AssignedTime"] = DateTime.UtcNow; } } // If the previous state was Working for the same agent it's AssignedTo, // then we can clear the AssignedTo field if (PreviousInfo.State == AgentState.Working) { string PreviousAssignedTo = PreviousInfo.Configuration["AssignedTo"] as string; if (PreviousAssignedTo == PreviousWorkingFor) { PreviousInfo.Configuration["AssignedTo"] = ""; PreviousInfo.Configuration["AssignedTime"] = DateTime.UtcNow; } } } else { // If it's WorkingFor someone, but not AssignedTo anyone else, update the AssignedTo if (((UpdatedInfo.Configuration["WorkingFor"] as string) != "") && ((PreviousInfo.Configuration["AssignedTo"] as string) == "")) { PreviousInfo.Configuration["AssignedTo"] = UpdatedInfo.Configuration["WorkingFor"]; PreviousInfo.Configuration["AssignedTime"] = DateTime.UtcNow; } } string UpdatedAssignedTo = PreviousInfo.Configuration["AssignedTo"] as string; UpdatedInfo.Configuration["AssignedTo"] = UpdatedAssignedTo; UpdatedInfo.Configuration["AssignedTime"] = DateTime.UtcNow; } // Set or reset the agent info to the latest Agents[UpdatedInfo.Name] = UpdatedInfo; } return(Response); }
private void checkOptions(object sender, EventArgs e) { if (loaded == true) { materialSkinManager.ColorScheme = new ColorScheme(Primary.Cyan400, Primary.Indigo700, Primary.Indigo100, Accent.LightGreen200, TextShade.WHITE); materialSkinManager.Theme = MaterialSkinManager.Themes.DARK; return; } loaded = true; try { Ping myPing = new Ping(); String host = "google.com"; byte[] buffer = new byte[32]; int timeout = 1000; PingOptions pingOptions = new PingOptions(); PingReply reply = myPing.Send(host, timeout, buffer, pingOptions); internet = true; } catch { this.Style = MetroColorStyle.Red; materialSkinManager.ColorScheme = new ColorScheme(Primary.Red600, Primary.Indigo700, Primary.Indigo100, Accent.LightGreen200, TextShade.WHITE); internet = false; newsTitle.Text = translateDic["errorInternet"]; notifView(translateDic["errorInternet"]); errorImage.BringToFront(); return; } try { var client = new RestClient(apiUrl); var request = new RestRequest("api/settings", Method.GET); IRestResponse response = client.Execute(request); var content = response.Content; dynamic res = JObject.Parse(content.ToString()); if (res.maintenance == "1") { maintenance = true; loginButton.Enabled = false; registerLink.Enabled = false; materialSkinManager.ColorScheme = new ColorScheme(Primary.Orange400, Primary.Indigo700, Primary.Indigo100, Accent.LightGreen200, TextShade.WHITE); this.Style = MetroColorStyle.Orange; if (res.maintenance_title == "{picture}") { newsImage.Visible = true; newsImage.ImageLocation = res.maintenance_content; newsImage.BringToFront(); } else { newsTitle.Text = res.maintenance_title; newsContent.Text = res.maintenance_content; } maintenanceRefresh.RunWorkerAsync(); return; } if (res.msg_title == "{picture}") { newsImage.Visible = true; newsImage.ImageLocation = res.msg_content; newsImage.BringToFront(); } newsTitle.Text = res.msg_title; newsContent.Text = res.msg_content; if (modDev == false && res.vlauncher != getLauncherMd5().ToLower()) { launcherUpdate(); return; } if (res.login == "0") { sessionToken = null; startLauncher = false; loginUsername.Text = ""; loginPassword.Text = ""; loginRemember.Checked = false; this.Visible = false; if (!File.Exists(appdata + communityName + "/autoConnect")) { using (var chooseServer = new serverChoose(apiUrl, communityName, translateDic, appdata)) { var result = chooseServer.ShowDialog(); if (result == DialogResult.OK) { serverID = chooseServer.currentServerid; serverIP = chooseServer.currentServerIP; serverGame = chooseServer.currentServerGame; serverName = chooseServer.currentServerName; getServerInfo(serverID); } } } else { string id = File.ReadAllText(appdata + communityName + "/autoConnect"); //GET SERVER INFO getServerInfo(id); } switch (serverGame) { case "arma3": using (var launcher = new launcherMain(communityName, apiUrl, webSite, teamSpeak, sessionToken, ftp_url, ftp_user, ftp_pass, vLast, taskforce, vtaskforce, modDev, serverIP, translateDic, showIGinfo, serverName, serverID, modPackName, downloadPath, serverLocked, serverMaintenance, serverPass)) { var result = launcher.ShowDialog(); if (result == DialogResult.Yes) { if (File.Exists(appdata + communityName + "/autoConnect")) { File.Delete(appdata + communityName + "/autoConnect"); } loginWithToken(); } } break; default: MessageBox.Show("This game is not created on this launcher"); break; } materialSkinManager.Theme = MaterialSkinManager.Themes.DARK; this.Visible = true; } if (res.register == "0") { registerLink.Enabled = false; registerMessage.Text = translateDic["registerDisabled"]; } if (sessionToken != null) { loginWithToken(); } server = true; } catch { this.Style = MetroColorStyle.Red; materialSkinManager.ColorScheme = new ColorScheme(Primary.Red600, Primary.Indigo700, Primary.Indigo100, Accent.LightGreen200, TextShade.WHITE); server = false; newsTitle.Text = translateDic["error404"]; notifView(translateDic["error404"]); newsContent.Visible = false; newsImage.Visible = false; errorImage.BringToFront(); } }
private void Timer1_Tick(object sender, EventArgs e) { try { timer1.Enabled = false; if (mControl.isRunning == false) { if (ClientConnection == false) { if (CheckToPing == true) { PingLast = mControl.공용함수.timeGetTimems(); if (3000 <= (PingLast - PingFirst)) { Ping ping = new Ping(); PingReply r = ping.Send(ClientIpAddr.IP); if (r.Status == IPStatus.Success) { //CheckToPingCount++; //if (CheckToPingCount <= 10) // TCPOpen(); //else CheckToPing = false; //if (CheckToPing == false) //{ // if (MessageBox.Show("서버PC 와 통신 연결이 되지 않습니다.\n연결 작업을 다시 진행하시겠습니까?", "확인", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes) // { // CheckToPingCount = 0; // CheckToPing = true; // } //} TCPOpen(); CheckToPingCount = 0; } else { if (100 < CheckToPingCount) { CheckToPing = false; //5분간 Ping 이 붇지 않는다면 } //if (CheckToPing == false) //{ // if (MessageBox.Show("서버PC 와 통신 연결이 되지 않습니다.\n연결 작업을 다시 진행하시겠습니까?", "확인", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes) // { // CheckToPingCount = 0; // CheckToPing = true; // } //} } PingFirst = mControl.공용함수.timeGetTimems(); PingLast = mControl.공용함수.timeGetTimems(); } } else { long OneMinth = (1000 * 60); //1분 PingLast = mControl.공용함수.timeGetTimems(); //15분 후 다시 ping 을 시도한다. if ((OneMinth * 15) <= (PingLast - PingFirst)) { CheckToPingCount = 0; CheckToPing = true; PingFirst = mControl.공용함수.timeGetTimems(); PingLast = mControl.공용함수.timeGetTimems(); } } } else { if (0 < CheckToPingCount) { CheckToPingCount = 0; } } } } catch { } finally { timer1.Enabled = true; } return; }
void sendTrace() { Ping pingSender = new Ping(); PingOptions options = new PingOptions(); int ttl = 1; options.DontFragment = true; IPAddress[] IPs = null; try { IPs = Dns.GetHostEntry(hostbox.Text.Trim()).AddressList; } catch (SocketException e) { Update_Button(sendit, true); Update_Button(stopit, false); SetText(results, e.Message + "\r\n"); return; } int hops = 0, timeout = 0; try { hops = Convert.ToInt32(databox.Text.Trim()); timeout = Convert.ToInt32(databox2.Text.Trim()); } catch (FormatException e) { Update_Button(sendit, true); Update_Button(stopit, false); SetText(results, e.Message + "\r\n"); return; } SetText(results, "-----------------------------------\r\nTracing route to " + hostbox.Text + " [" + IPs[0] + "]\r\n"); while (traceing && ttl <= hops) { PingReply reply = null; options.Ttl = ttl; try { reply = pingSender.Send(hostbox.Text.Trim(), timeout, new byte[0], options); } catch (PingException e) { Update_Button(sendit, true); Update_Button(stopit, false); //SetText(results, " Interrupted\r\n"); Console.WriteLine(e.Message); return; } if (reply.Status == IPStatus.Success) { traceing = false; } SetText(results, " " + ttl.ToString()); try { PingReply timing = pingSender.Send(reply.Address, timeout, new byte[32], new PingOptions(128, true)); SetText(results, (timing.Status == IPStatus.Success) ? "\t" + timing.RoundtripTime.ToString() + "ms" : "\t*"); timing = pingSender.Send(reply.Address, timeout, new byte[32], new PingOptions(128, true)); SetText(results, (timing.Status == IPStatus.Success) ? "\t" + timing.RoundtripTime.ToString() + "ms" : "\t*"); timing = pingSender.Send(reply.Address, timeout, new byte[32], new PingOptions(128, true)); SetText(results, (timing.Status == IPStatus.Success) ? "\t" + timing.RoundtripTime.ToString() + "ms" : "\t*"); } catch (PingException e) { Update_Button(sendit, true); Update_Button(stopit, false); SetText(results, " Interrupted\r\n"); Console.WriteLine(e.Message); return; } catch (ArgumentNullException e) { //SetText(results, "\t\t"); Console.WriteLine(e.Message); } string hostName = null; if (databox3.Checked) { try { IPHostEntry hostEntry = Dns.GetHostEntry(reply.Address); if (hostEntry.HostName != null && hostEntry.HostName != string.Empty) { hostName = hostEntry.HostName; } } catch (ArgumentNullException e) { hostName = reply.Status.ToString(); Console.WriteLine(e.Message); } catch (SocketException e) { hostName = reply.Address.ToString(); Console.WriteLine(e.Message); } } else { try { hostName = reply.Address.ToString(); } catch (NullReferenceException e) { hostName = reply.Status.ToString(); Console.WriteLine(e.Message); } } SetText(results, "\t" + hostName + "\r\n"); ttl++; } SetText(results, ((!traceing) ? "Trace complete\r\n" : "Trace Stopped, ttl expired\r\n")); pingSender.Dispose(); Update_Button(sendit, true); Update_Button(stopit, false); }
public IList <Track> Search(string query) { var result = new List <Track>(); try { Ping pinger = new Ping(); PingOptions pingerOptions = new PingOptions(255, true); string data = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"; byte[] buffer = Encoding.ASCII.GetBytes(data); int timeout = 60000; string hostName = @"vk.com"; PingReply reply = pinger.Send(hostName, timeout, buffer, pingerOptions); if (reply.Status != IPStatus.Success) { return(new ReadOnlyCollection <Track>(result)); } if (_cookie == null) { var res = Auth(Config.GetInstance().VKLogin, Config.GetInstance().VKPassword, out _cookie); if (!res) { throw new Exception("Failed to authorize at vk.com."); } } var url = "http://vk.com/gsearch.php?section=audio&q=" + HttpUtility.UrlEncode(query) + "&name=1"; HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest; request.CookieContainer = new CookieContainer(); request.CookieContainer.Add(_cookie); var responseStream = request.GetResponse().GetResponseStream(); string content = ""; using (var reader = new StreamReader(responseStream, Encoding.GetEncoding(1251))) { content = reader.ReadToEnd(); } Regex tableRegex = new Regex(@"(<table id=""searchResults""(.|\n)*>(.|\n)*)<td id=""filters""", RegexOptions.Multiline); content = tableRegex.Match(content).Groups[1].Value; content = StripHtmlEntities(content) + "</tr></table>"; // Нет метки о том, что ничего не найдено if (!content.Contains("noResults")) { var doc = XDocument.Load(new StringReader(content)); var td = doc.Root.XPathSelectElement("tr/td"); XElement tmpElement; Regex onclickRegex = new Regex(@"\((.*)\)"); foreach (var div in td.Elements()) { var track = new Track(); string onImgClick = div.XPathSelectElement("table/tbody/tr/td/img").Attribute("onclick").Value; var match = onclickRegex.Match(onImgClick); if (!match.Success) { continue; } var terms = match.Groups[1].Value.Replace("\'", "").Split(','); track.Uri = new Uri("http://cs" + terms[1] + ".vkontakte.ru/u" + terms[2] + "/audio/" + terms[3] + ".mp3"); tmpElement = div.XPathSelectElements("table/tbody/tr/td/div"). Where(el => el.Attribute("class").Value == "audioTitle").First(); track.Singer = tmpElement.XPathSelectElement("b").Value; track.Title = (from element in tmpElement.Elements("span") where (element.Attribute("id") != null) && element.Attribute("id").Value.Contains("title") select element.Value).First(); var duration = (from element in tmpElement.Parent.Elements("div") where element.Attribute("class").Value == "duration" select element.Value).First(); TimeSpan tmp; TimeSpan.TryParse("00:" + duration, out tmp); track.Duration = tmp; track.Source = TrackSource.VK; track.Id = track.GetHash(); result.Add(track); } } } catch (Exception e) { Console.WriteLine("VKComDataProvider error: " + e.Message); Console.WriteLine("Query: " + query); } return(new ReadOnlyCollection <Track>(result)); }
private void TraceRouteWorker_ProgressChanged(object sender, ProgressChangedEventArgs e) { PingReply reply = (PingReply)e.UserState; _hops.Add(new TraceRouteHopItemViewModel(new Models.TraceRouteHop(reply))); }
void ThreadRun() { while (true) // abort will take care of this { long latencyMinMs = long.MaxValue; ushort?latencyMinIdx = null; // This loop pings each known host one time, stores the result, // and determines the lowest ping time. for (ushort i = 0; i < hosts.Count(); ++i) { IPAddress host = hosts[i]; LinkedList <long?> results = Results[i]; const ushort MaxWaitMs = 2000; try { PingReply reply = ping.Send(host, MaxWaitMs); if (reply.Status != IPStatus.Success) { results.AddFirst((long?)null); // Must match #2 } else { // Successful ping reply results.AddFirst(reply.RoundtripTime); if (latencyMinIdx == null || reply.RoundtripTime < latencyMinMs) { latencyMinMs = reply.RoundtripTime; latencyMinIdx = i; } } } catch (PingException) { results.AddFirst((long?)null); // Must match #1 } if (results.Count > MaxNumResults) { results.RemoveLast(); } } // end of for-loop pinging every host // Now we know which host, if any, is fastest. if (latencyMinIdx != null) { ++FastestCount[latencyMinIdx.Value]; latestMinimumSample.status = SampleStatus.Good; latestMinimumSample.rttMs = latencyMinMs; // Update EMA ushort numEmaSamples = Math.Min(MaxNumResults, ++emaSamples); double alpha = 2.0 / (numEmaSamples + 1); // http://en.wikipedia.org/wiki/Moving_average#Exponential_moving_average ema = (ushort)Math.Round((latencyMinMs * alpha) + (ema * (1 - alpha))); Debug.WriteLine("EMA of " + numEmaSamples + " samples: " + ema); } else { ++TimedoutSamples; latestMinimumSample.status = SampleStatus.TimedOut; // Update EMA emaSamples = 0; } if (NewResultAvailable != null) { NewResultAvailable(this, null); } UpdateExternalRequestCount(); Thread.Sleep(timeBetweenSamples); } }
public PingReplyEnricher(PingReply pingReply) { _pingReply = pingReply; }
//thread to do ping public void startPing(string sHost, PingOptions pOptions) { System.Diagnostics.Debug.WriteLine("+++thread started"); string ipAddress = sHost; //make a local copy Ping myPing = new Ping(); PingOptions myPingOptions = pOptions; //make a local copy int iTimeout = pOptions.TimeOut; int _numberOfPings = pOptions.numOfPings; bool doNotFragment = pOptions.DontFragment; int bufferSize = pOptions.bufferSize; byte[] buf = new byte[bufferSize]; //long sumRoundtripTime=0; onReply(new PingReplyEventArgs("ping started...", PingReplyTypes.info)); replyStats _replyStats = new replyStats(ipAddress); PingReply reply = null; try { onReply(new PingReplyEventArgs(pOptions.ToString(), PingReplyTypes.info)); //check DNS first as this may block for long time IPAddress address; HostParms hostParms = new HostParms(ipAddress, 4); try { //is IP address address = IPAddress.Parse(ipAddress); hostParms.isValid = true; } catch { if (checkHost(ref hostParms)) { ipAddress = hostParms.ipAddress.ToString(); } } if (!hostParms.isValid) { throw new PingUnknownHostException("Unkown host: " + ipAddress); } for (int ix = 0; ix < _numberOfPings; ix++) { reply = myPing.Send(ipAddress, buf, iTimeout, myPingOptions); string sReply = ""; if (reply.Status == IPStatus.Success) { //sumRoundtripTime += reply.RoundTripTime; _replyStats.add(1, 1, reply.RoundTripTime); sReply = myResources.getReply(reply, ipAddress); } else if (reply.Status == IPStatus.DestinationHostUnreachable) { _replyStats.add(1, 0, reply.RoundTripTime); throw new PingUnknownHostException("Destination unreachable"); } else { _replyStats.add(1, 0, reply.RoundTripTime); sReply = myResources.getReply(reply, ipAddress); } System.Diagnostics.Debug.WriteLine(sReply); onReply(new PingReplyEventArgs(sReply)); } onReply(new PingReplyEventArgs(_replyStats.ToString(), PingReplyTypes.info)); } catch (PingUnknownHostException ex) { System.Diagnostics.Debug.WriteLine("PingUnknownHostException: " + ex.Message); onReply(new PingReplyEventArgs("Unknown host: " + ipAddress, PingReplyTypes.info)); } catch (PingException ex) { System.Diagnostics.Debug.WriteLine("PingException: " + ex.Message); } catch (ThreadAbortException ex) { onReply(new PingReplyEventArgs("ping failed", PingReplyTypes.info)); Thread.CurrentThread.Abort(); } catch (Exception ex) { System.Diagnostics.Debug.WriteLine("PingException: " + ex.Message); } finally { onReply(new PingReplyEventArgs("done", PingReplyTypes.done)); System.Diagnostics.Debug.WriteLine("---thread ended"); } }
private void Install() { Ping pingSender = new Ping(); IPAddress address = IPAddress.Parse("127.0.0.1"); PingReply reply = pingSender.Send(address); if (reply.Status == IPStatus.Success) { for (int I = 0; I <= Files.Length; I++) { if (!(I == Files.Length)) { string xFile = Files[I]; if (xFile.EndsWith("/") == true) { Directory.CreateDirectory(textBox1.Text + Files[I].Replace("(Dir)", "")); InstallFile.Text = Files[I]; progressBar1.Value = 100 / (Files.Length - I); } else { try { string[] x1File = xFile.Split('/'); string FilePath = textBox1.Text + xFile; InstallFile.Text = x1File[x1File.Length]; System.Net.WebClient zz = new System.Net.WebClient(); zz.DownloadFile(fileHost + xFile, FilePath); } catch { string FilePath = textBox1.Text + xFile; InstallFile.Text = xFile; System.Net.WebClient zz = new System.Net.WebClient(); zz.DownloadFile(fileHost + xFile, FilePath); } } } else { label10.Text = "Completed"; InstallFile.Text = ""; Back.Enabled = false; Next.Enabled = true; panel3.Visible = false; panel4.Left = panel1.Left; panel4.Top = panel1.Top; panel4.Visible = true; label3.BackColor = Color.Transparent; label4.BackColor = Color.FromArgb(70, 255, 255, 255); Next.Text = "&Finish"; rad4.Checked = true; } } } else { panel3.Visible = false; label9.Text = "Abort..."; label11.Text = "You are not connected to the internet. \nPress back, to restart."; panel4.Left = panel1.Left; panel4.Top = panel1.Top; Next.Text = "&Finish"; Next.Enabled = false; panel4.Visible = true; rad4.Checked = true; checkBox1.Visible = false; checkBox1.Checked = false; rad3.Checked = false; rad3.BackColor = Color.DarkRed; label3.BackColor = Color.Transparent; label4.BackColor = Color.FromArgb(70, 255, 255, 255); } }
public void scan1() { string StartIP = textBox2.Text; int l = StartIP.LastIndexOf(".", StartIP.Length); string startip = StartIP.Substring(0, l); string EndIP = startip + "." + "255"; foo : while (!_shouldstop) { try { IPAddress ip = IPAddress.Parse(StartIP); IPAddress ip2 = IPAddress.Parse(EndIP); IPAddress ipScan = null; string hostname = null; int[] aa = new int[4], bb = new int[4]; //Get first, second, … byte of address aa[0] = Convert.ToInt32(ip.GetAddressBytes()[0]); aa[1] = Convert.ToInt32(ip.GetAddressBytes()[1]); aa[2] = Convert.ToInt32(ip.GetAddressBytes()[2]); aa[3] = Convert.ToInt32(ip.GetAddressBytes()[3]); bb[0] = Convert.ToInt32(ip2.GetAddressBytes()[0]); bb[1] = Convert.ToInt32(ip2.GetAddressBytes()[1]); bb[2] = Convert.ToInt32(ip2.GetAddressBytes()[2]); bb[3] = Convert.ToInt32(ip2.GetAddressBytes()[3]); for (int a = aa[0]; a <= bb[0]; a++) { for (int b = aa[1]; b <= bb[1]; b++) { for (int c = aa[2]; c <= bb[2]; c++) { for (int d = aa[3]; d <= bb[3]; d++) { if (!_shouldstop) { ipScan = IPAddress.Parse(a.ToString() + "." + b.ToString() + "." + c.ToString() + "." + d.ToString()); Ping pingSender = new Ping(); PingOptions options = new PingOptions(); options.DontFragment = true; string data = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"; byte[] buffer = Encoding.ASCII.GetBytes(data); int timeout = 150; PingReply reply = pingSender.Send(ipScan, timeout, buffer, options); hostname = null; string macaddr = null; if (reply.Status == IPStatus.Success) { //hostname = GetHostName(ipScan); macaddr = GetMacUsingARP(ipScan.ToString()); ListViewItem itm = new ListViewItem(ipScan.ToString()); //itm.SubItems.Add(hostname); itm.SubItems.Add(macaddr); delupdateUi updatelist = new delupdateUi(updateUi); this.ListView1.Invoke(updatelist, itm); //ListView1.Items.Add(itm); } } else { goto foo; } } } } } } catch (Exception ex) { MessageBox.Show(ex.ToString()); } RequesStop(); _finished = true; delupdateStatus delupdatebutton = new delupdateStatus(updateButton); this.button1.Invoke(delupdatebutton); } }
//ping each host private void pingHost() { //try try { //if host string exists if (host.Length > 0) { //ping host Ping objping = new Ping(); PingReply objpingreply = objping.Send(host, 1000); //if ping was successfull if (objpingreply.Status == IPStatus.Success) { //import data for the whitelists - added after application was written ImportData(); //print out that ping succeeded //string pingable = System.String.Concat("\n" + host + " ,is alive\n"); string pingable = System.String.Concat("\nPing " + objpingreply.Status.ToString() + " to " + host + "\n"); Output.AppendText(pingable); //go to OS check //if os is win7 if (GETOSMethod().Contains("Windows 7")) { //go to this subroutine Win7Enumerate(); } //if os is winxp else if (GETOSMethod().Contains("XP")) { //go to enumerate //send host to readXML section enumerate(); } //if os is not XP or 7 else { //break and show user error Close(); } } //if ping failed else { //print out that ping has failed //string notpingable = System.String.Concat("\n" + host + " ,is dead\n"); string notpingable = System.String.Concat("\nPing " + objpingreply.Status.ToString() + " to " + host + "\nAll operations aborted for " + host); Output.AppendText(notpingable); } } //update progess bar progresbarupdate(); } //catch all exceptions catch (Exception ex) { Output.AppendText(ex.Message + "\n"); MessageBox.Show("ERROR: Host " + host + " does not exist.\n" + ex.Message + "\n\nUse Ctrl+C to copy to clipboard"); //throw; } }
internal PingReplyData(PingReply reply) { this.reply = reply; }
public static async Task Ping(SocketMessage message, string[] arg, string msg) { Ping p = new Ping(); PingReply reply = p.Send("discordapp.com"); await message.Channel.SendMessageAsync($":white_check_mark: `{reply.RoundtripTime}ms`"); }
protected void PingTester(Dictionary <string, string> servers) { Ping pingSender = new Ping(); // Create a buffer of 32 bytes of data to be transmitted. string data = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"; byte[] buffer = Encoding.ASCII.GetBytes(data); // Wait 10 seconds for a reply. int timeout = 10000; PingOptions options = new PingOptions(64, true); int row = 1; foreach (KeyValuePair <string, string> pair in servers) { PingReply reply = pingSender.Send(pair.Value, timeout, buffer, options); SomeGrid.RowDefinitions.Add(new RowDefinition()); TextBlock thisServer = new TextBlock(); thisServer.Text = pair.Key; thisServer.HorizontalAlignment = HorizontalAlignment.Center; thisServer.Margin = new Thickness(0, 5, 0, 5); thisServer.Padding = new Thickness(5, 5, 5, 5); SomeGrid.Children.Add(thisServer); Grid.SetColumn(thisServer, 0); Grid.SetRow(thisServer, row); Ellipse thisEllipse = new Ellipse(); thisEllipse.Width = 10; thisEllipse.Height = 10; thisEllipse.Margin = new Thickness(10, 10, 10, 10); thisEllipse.HorizontalAlignment = HorizontalAlignment.Left; SomeGrid.Children.Add(thisEllipse); Grid.SetColumn(thisEllipse, 1); Grid.SetRow(thisEllipse, row); TextBox statusBox = new TextBox(); statusBox.Text = "Waiting..."; statusBox.Padding = new Thickness(5, 5, 5, 5); statusBox.Margin = new Thickness(10, 5, 10, 5); statusBox.MinWidth = 75; statusBox.MaxWidth = 75; statusBox.HorizontalAlignment = HorizontalAlignment.Right; SomeGrid.Children.Add(statusBox); Grid.SetColumn(statusBox, 1); Grid.SetRow(statusBox, row); TextBox latencyBox = new TextBox(); latencyBox.Text = "0 ms"; latencyBox.Margin = new Thickness(0, 5, 0, 5); latencyBox.Padding = new Thickness(10, 5, 10, 5); statusBox.MinWidth = 75; statusBox.MaxWidth = 75; latencyBox.HorizontalAlignment = HorizontalAlignment.Center; SomeGrid.Children.Add(latencyBox); Grid.SetColumn(latencyBox, 2); Grid.SetRow(latencyBox, row); if (reply.Status == IPStatus.Success) { thisEllipse.Fill = new SolidColorBrush(Colors.Green); statusBox.Text = "Success!"; latencyBox.Text = reply.RoundtripTime + " ms"; } else { thisEllipse.Fill = new SolidColorBrush(Colors.Red); statusBox.Text = "Failed!"; } row++; } }
public ExceptionCode Open() { byte[] bReceive = new byte[256]; try { // check if available Ping p = new Ping(); PingReply pingReplay = p.Send(IP); if (pingReplay.Status != IPStatus.Success) { throw new Exception(); } } catch { lastErrorCode = ExceptionCode.IPAdressNotAvailable; lastErrorString = "Destination IP-Address '" + IP + "' is not available!"; //lastErrorString = "Địa chỉ IP '" + IP + "' không tồn tại!"; return(lastErrorCode); } try { // open the channel mSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); mSocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveTimeout, 3000); mSocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.SendTimeout, 3000); IPEndPoint _server = new IPEndPoint(new IPAddress(IPToByteArray(IP)), 102); //Dns.GetHostEntry(mIP).AddressList(0), 102) IPEndPoint _local = new IPEndPoint(Dns.GetHostEntry(Dns.GetHostName()).AddressList[0], 102); mSocket.Connect(_server); } catch (Exception ex) { lastErrorCode = ExceptionCode.ConnectionError; lastErrorString = ex.Message; return(ExceptionCode.ConnectionError); } try { byte[] bSend1 = { 3, 0, 0, 22, 17, 224, 0, 0, 0, 46, 0, 193, 2, 1, 0, 194, 2, 3, 0, 192, 1, 9 }; switch (CPU) { case CPU_Type.S7200: //S7200: Chr(193) & Chr(2) & Chr(16) & Chr(0) 'Eigener Tsap bSend1[11] = 193; bSend1[12] = 2; bSend1[13] = 16; bSend1[14] = 0; //S7200: Chr(194) & Chr(2) & Chr(16) & Chr(0) 'Fremder Tsap bSend1[15] = 194; bSend1[16] = 2; bSend1[17] = 16; bSend1[18] = 0; break; case CPU_Type.S71200: case CPU_Type.S7300: //S7300: Chr(193) & Chr(2) & Chr(1) & Chr(0) 'Eigener Tsap bSend1[11] = 193; bSend1[12] = 2; bSend1[13] = 1; bSend1[14] = 0; //S7300: Chr(194) & Chr(2) & Chr(3) & Chr(2) 'Fremder Tsap bSend1[15] = 194; bSend1[16] = 2; bSend1[17] = 3; bSend1[18] = (byte)(Rack * 2 * 16 + Slot); break; case CPU_Type.S7400: //S7400: Chr(193) & Chr(2) & Chr(1) & Chr(0) 'Eigener Tsap bSend1[11] = 193; bSend1[12] = 2; bSend1[13] = 1; bSend1[14] = 0; //S7400: Chr(194) & Chr(2) & Chr(3) & Chr(3) 'Fremder Tsap bSend1[15] = 194; bSend1[16] = 2; bSend1[17] = 3; bSend1[18] = (byte)(Rack * 2 * 16 + Slot); break; default: return(ExceptionCode.WrongCPU_Type); } mSocket.Send(bSend1, 22, SocketFlags.None); if (mSocket.Receive(bReceive, 22, SocketFlags.None) != 22) { throw new Exception(ExceptionCode.WrongNumberReceivedBytes.ToString()); } byte[] bsend2 = { 3, 0, 0, 25, 2, 240, 128, 50, 1, 0, 0, 255, 255, 0, 8, 0, 0, 240, 0, 0, 3, 0, 3, 1, 0 }; mSocket.Send(bsend2, 25, SocketFlags.None); if (mSocket.Receive(bReceive, 27, SocketFlags.None) != 27) { throw new Exception(ExceptionCode.WrongNumberReceivedBytes.ToString()); } IsConnected = true; } catch { lastErrorCode = ExceptionCode.ConnectionError; lastErrorString = "Couldn't establish the connection!"; //lastErrorString = "Không thể thành lập được kết nối tới PLC!"; IsConnected = false; return(ExceptionCode.ConnectionError); } return(ExceptionCode.ExceptionNo); // ok }
public SelectServer(String windowName = "") { InitializeComponent(); if (windowName != "") { this.Text = windowName; } //And one for keeping data about server, IP tbh Dictionary <int, ServerInfo> data = new Dictionary <int, ServerInfo>(); ServerListRenderer.View = View.Details; ServerListRenderer.FullRowSelect = true; ServerListRenderer.Columns.Add(""); ServerListRenderer.Columns[0].Width = 1; ServerListRenderer.Columns.Add("Name"); ServerListRenderer.Columns[1].Width = 220; ServerListRenderer.Columns.Add("Country"); ServerListRenderer.Columns[2].Width = 80; ServerListRenderer.Columns.Add("Players Online"); ServerListRenderer.Columns[3].Width = 80; ServerListRenderer.Columns[3].TextAlign = HorizontalAlignment.Right; ServerListRenderer.Columns.Add("Registered Players"); ServerListRenderer.Columns[4].Width = 100; ServerListRenderer.Columns[4].TextAlign = HorizontalAlignment.Right; ServerListRenderer.Columns.Add("Ping"); ServerListRenderer.Columns[5].Width = 55; ServerListRenderer.Columns[5].TextAlign = HorizontalAlignment.Right; //Actually accept JSON instead of old format// List <ServerInfo> serverInfos = new List <ServerInfo>(); //foreach (var serverListURL in Self.serverlisturl) { try { var wc = new WebClientWithTimeout(); var response = wc.DownloadString(Self.serverlisturl[0]); try { serverInfos.AddRange(JsonConvert.DeserializeObject <List <ServerInfo> >(response)); } catch (Exception error) { Log.Error("Error occurred while deserializing server list from [" + Self.serverlisturl[0] + "]: " + error.Message); } } catch (Exception error) { Log.Error("Error occurred while loading server list from [" + Self.serverlisturl[0] + "]: " + error.Message); } //} if (File.Exists("servers.json")) { var fileItems = JsonConvert.DeserializeObject <List <ServerInfo> >(File.ReadAllText("servers.json")); if (fileItems.Count > 0) { fileItems.Select(si => { si.DistributionUrl = ""; si.DiscordPresenceKey = ""; si.Id = SHA.HashPassword($"{si.Name}:{si.Id}:{si.IpAddress}"); si.IsSpecial = false; si.Category = "CUSTOM"; return(si); }).ToList().ForEach(si => serverInfos.Add(si)); } } List <ServerInfo> newFinalItems = new List <ServerInfo>(); foreach (ServerInfo xServ in serverInfos) { if (newFinalItems.FindIndex(i => string.Equals(i.Name, xServ.Name)) == -1) { newFinalItems.Add(xServ); } } foreach (var substring in newFinalItems) { try { servers.Enqueue(ID + "_|||_" + substring.IpAddress + "_|||_" + substring.Name); ServerListRenderer.Items.Add(new ListViewItem( new[] { ID.ToString(), substring.Name, "", "", "", "", "" } )); data.Add(ID, substring); ID++; } catch { } } Thread newList = new Thread(() => { Thread.Sleep(200); this.BeginInvoke((MethodInvoker) delegate { while (servers.Count != 0) { string QueueContent = servers.Dequeue(); string[] QueueContent2 = QueueContent.Split(new string[] { "_|||_" }, StringSplitOptions.None); int serverid = Convert.ToInt32(QueueContent2[0]) - 1; string serverurl = QueueContent2[1] + "/GetServerInformation"; string servername = QueueContent2[2]; try { WebClientWithTimeout getdata = new WebClientWithTimeout(); getdata.Timeout(1000); GetServerInformation content = JsonConvert.DeserializeObject <GetServerInformation>(getdata.DownloadString(serverurl)); if (content == null) { ServerListRenderer.Items[serverid].SubItems[1].Text = servername; ServerListRenderer.Items[serverid].SubItems[2].Text = "N/A"; ServerListRenderer.Items[serverid].SubItems[3].Text = "N/A"; ServerListRenderer.Items[serverid].SubItems[4].Text = "---"; } else { ServerListRenderer.Items[serverid].SubItems[1].Text = servername; ServerListRenderer.Items[serverid].SubItems[2].Text = Self.CountryName(content.country.ToString()); ServerListRenderer.Items[serverid].SubItems[3].Text = content.onlineNumber.ToString(); ServerListRenderer.Items[serverid].SubItems[4].Text = content.numberOfRegistered.ToString(); //PING if (!DetectLinux.LinuxDetected()) { Ping pingSender = new Ping(); Uri StringToUri = new Uri(serverurl); pingSender.SendAsync(StringToUri.Host, 1000, new byte[1], new PingOptions(64, true), new AutoResetEvent(false)); pingSender.PingCompleted += (sender3, e3) => { PingReply reply = e3.Reply; if (reply.Status == IPStatus.Success && servername != "Offline Built-In Server") { ServerListRenderer.Items[serverid].SubItems[5].Text = reply.RoundtripTime + "ms"; } else { ServerListRenderer.Items[serverid].SubItems[5].Text = "---"; } }; } else { ServerListRenderer.Items[serverid].SubItems[5].Text = "---"; } } } catch { ServerListRenderer.Items[serverid].SubItems[1].Text = servername; ServerListRenderer.Items[serverid].SubItems[3].Text = "N/A"; ServerListRenderer.Items[serverid].SubItems[4].Text = "N/A"; ServerListRenderer.Items[serverid].SubItems[5].Text = "---"; } if (servers.Count == 0) { loading.Text = ""; } Application.DoEvents(); } }); }); newList.IsBackground = true; newList.Start(); ServerListRenderer.AllowColumnReorder = false; ServerListRenderer.ColumnWidthChanging += (handler, args) => { args.Cancel = true; args.NewWidth = ServerListRenderer.Columns[args.ColumnIndex].Width; }; ServerListRenderer.DoubleClick += new EventHandler((handler, args) => { if (ServerListRenderer.SelectedItems.Count == 1) { rememberServerInformationID.TryGetValue(ServerListRenderer.SelectedIndices[0], out ServerInfo); MainScreen.ServerName = data[ServerListRenderer.SelectedIndices[0] + 1]; this.Close(); } }); }
private void Timer1_Tick(object sender, EventArgs e) { try { timer1.Enabled = false; if (ClientConnection == false) { if (CheckToPing == true) { PingLast = mControl.PublicFunc.timeGetTimems(); if (1000 <= (PingLast - PingFirst)) { Ping ping = new Ping(); PingReply r = ping.Send(ClientIpAddr.IP); if (r.Status == IPStatus.Success) { CheckToPingCount++; if (CheckToPingCount <= 3) { TCPOpen(); } else { CheckToPing = false; } if (CheckToPing == false) { if (MessageBox.Show("서버PC 와 통신 연결이 되지 않습니다.\n연결 작업을 다시 진행하시겠습니까?", "확인", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes) { CheckToPingCount = 0; CheckToPing = true; } } } else { CheckToPing = false; if (MessageBox.Show("서버PC 와 통신 연결이 되지 않습니다.\n연결 작업을 다시 진행하시겠습니까?", "확인", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes) { CheckToPingCount = 0; CheckToPing = true; } } PingFirst = mControl.PublicFunc.timeGetTimems(); PingLast = mControl.PublicFunc.timeGetTimems(); } } } } catch { } finally { timer1.Enabled = true; } return; }
///////////////////////////////////////// FORWARD TRACEROUTE ////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// public void Traceroute(string ipAddressOrHostName, string dirname) { IPAddress ipAddress = Dns.GetHostEntry(ipAddressOrHostName).AddressList[0]; StringBuilder traceResults = new StringBuilder(); using (Ping pingSender = new Ping()) { PingOptions pingOptions = new PingOptions(); Stopwatch stopWatch = new Stopwatch(); byte[] bytes = new byte[32]; pingOptions.DontFragment = true; pingOptions.Ttl = 1; int maxHops = 30; traceResults.AppendLine(string.Format("Tracing route to {0}\n over a maximum of {1} hops:", ipAddress, maxHops)); for (int i = 1; i < maxHops + 1; i++) { stopWatch.Reset(); stopWatch.Start(); PingReply pingReply = pingSender.Send(ipAddress, 5000, new byte[32], pingOptions); stopWatch.Stop(); ListBox2.Visible = true; ListBox2.Items.Add(string.Format("{0}\t{1} \t{2} ms\n", i, pingReply.Address, stopWatch.ElapsedMilliseconds)); File.AppendAllText(Server.MapPath("~/App_Data/" + dirname + "/ftr.txt"), string.Format("{0}\t{1}ms \t{2}\n", i, stopWatch.ElapsedMilliseconds, pingReply.Address + Environment.NewLine)); if (pingReply.Status == IPStatus.Success) { File.AppendAllText(Server.MapPath("~/App_Data/" + dirname + "/ftr.txt"), "Trace complete."); break; } pingOptions.Ttl++; } } System.IO.StreamReader FTrfile = new System.IO.StreamReader(Server.MapPath("~/App_Data/" + dirname + "/ftr.txt")); string Ftext = FTrfile.ReadToEnd(); FTrfile.Close(); List <string> FipS = new List <string>(); List <string> Frttave = new List <string>(); string Flinepattern = @"(\d+[\t].*)"; string FIP = @"\b(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\b"; string Frttpattern = @"[\t]\d+ms [\t]"; MatchCollection Rtrline = Regex.Matches(Ftext, Flinepattern); foreach (Match Rlinematch in Rtrline) { string eline = Rlinematch.Value; int star = 0; Match Fmatchms = Regex.Match(eline, FIP); Match Frtt = Regex.Match(eline, Frttpattern); if (Fmatchms.Success) { FipS.Add(Fmatchms.ToString()); // ListBox1.Items.Add(Fmatchms.ToString()); } else { FipS.Add("0"); Frttave.Add("0"); // ListBox2.Items.Add("NO RTT FOR U"); star = 1; } if (star != 1) { if (Frtt.Success) { string Rrtttemp = Frtt.Value; char Rendchar = '\t'; string Rtrimen = Rrtttemp.TrimStart(Rendchar); string Rtrimst = Rtrimen.TrimEnd(Rendchar); Frttave.Add(Rtrimst); } } } /////////////////////////// FINDING LONGITUDE & LATITUDE OF FORWARD IPS ///////////////////////////////////////////////// List <string> Flonlat = new List <string>(); foreach (string item in FipS) { if (item != "0") { string URL1 = "http://www.geoiptool.com/en/?IP=IPADD"; URL1 = URL1.Replace("IPADD", item); WebRequest objRequest = HttpWebRequest.Create(URL1); objResponse = objRequest.GetResponse(); using (StreamReader sr = new StreamReader(objResponse.GetResponseStream())) { strResult = sr.ReadToEnd(); sr.Close(); } File.WriteAllText(Server.MapPath("~/App_Data/" + dirname + "/FLongLat.txt"), strResult); System.IO.StreamReader geoipfile = new System.IO.StreamReader(Server.MapPath("~/App_Data/" + dirname + "/FLongLat.txt")); string FLLtext = geoipfile.ReadToEnd(); geoipfile.Close(); int found_match = 0; MatchCollection Flonglat = Regex.Matches(FLLtext, @"(>-?\d{1,3}<)|(>-?\d{1,3}[.]\d{0,4}<)"); foreach (Match Fll in Flonglat) { string lltemp = Fll.Value; char Fendchar = '<'; char Fstartchar = '>'; string lltrimen = lltemp.TrimEnd(Fendchar); string lltrimst = lltrimen.TrimStart(Fstartchar); Flonlat.Add(lltrimst); found_match = found_match + 1; } if (found_match != 2) // If Longitude Latitude are not found by GEOIPtool { Flonlat.Add("0"); Flonlat.Add("0"); } } else { Flonlat.Add("0"); Flonlat.Add("0"); } } GenerateFMap(Flonlat, FipS, Frttave, dirname); }
public void CreateTableHost(List <Host> addressHost, int timeoutHost) { Ping Pinger = new Ping(); PingOptions options = new PingOptions(); options.DontFragment = true; String HostName = ""; List <String> tempHostName = new List <String>(); List <String> tempIpAddress = new List <String>(); List <String> tempDescription = new List <String>(); List <int> tempQualityHost = new List <int>(); List <long> tempRoadTrip = new List <long>(); outputDataPinger line = new outputDataPinger(); Console.Clear(); Console.Write(" \n Идет обработка доступности адресов, пожалуйста подождите..."); for (long iterator = 1; ; iterator++) { if (NetworkInterface.GetIsNetworkAvailable()) { for (int i = 0; i < addressHost.Count; i++) { Host tempListHost = addressHost[i]; HostName = tempListHost.hostName; try { PingReply ReplyInputDataHost = Pinger.Send(HostName, timeoutHost); if (ReplyInputDataHost.Status != IPStatus.Success) { tempHostName.Add(HostName); tempIpAddress.Add("not available"); tempRoadTrip.Add(ReplyInputDataHost.RoundtripTime); tempDescription.Add(tempListHost.physLocationHost); tempQualityHost.Add(tempListHost.Quality(false)); } else { try { tempHostName.Add(HostName); tempIpAddress.Add(ReplyInputDataHost.Address.ToString()); tempRoadTrip.Add(ReplyInputDataHost.RoundtripTime); tempDescription.Add(tempListHost.physLocationHost); tempQualityHost.Add(tempListHost.Quality(true)); } catch (NullReferenceException) { tempHostName.Add(HostName); tempIpAddress.Add("not available"); tempRoadTrip.Add(0); tempDescription.Add(tempListHost.physLocationHost); tempQualityHost.Add(tempListHost.Quality(false)); } } } catch (PingException) { tempHostName.Add(HostName); tempIpAddress.Add("HOST NAME ERROR!"); tempRoadTrip.Add(0); tempDescription.Add(tempListHost.physLocationHost); tempQualityHost.Add(tempListHost.Quality(false)); } catch (ArgumentException) { tempHostName.Add(HostName); tempIpAddress.Add("HOST NAME ERROR!"); tempRoadTrip.Add(0); tempDescription.Add(tempListHost.physLocationHost); tempQualityHost.Add(tempListHost.Quality(false)); } /*////////////////////////////////////////////////////////////////////// * /// РАЗОБРАТЬСЯ С РАБОТОЙ ИСКЛЮЧЕНИЙ, что и когда перехватывают * * catch (ObjectDisposedException) * { * tempHostName.Add(HostName); * tempIpAddress.Add("ObjectDisposedException!"); * tempRoadTrip.Add(999); * tempDescription.Add(tempListHost.physLocationHost); * tempQualityHost.Add(tempListHost.Quality(false)); * } * catch (InvalidOperationException) * { * tempHostName.Add(HostName); * tempIpAddress.Add("InvalidOperationException"); * tempRoadTrip.Add(999); * tempDescription.Add(tempListHost.physLocationHost); * tempQualityHost.Add(tempListHost.Quality(false)); * } * //////////////////////////////////////////////////////////////////*/ } Console.Clear(); line.writeHeadTable(); for (int i = 0; i < addressHost.Count; i++) { line.writeTextColor(tempHostName[i], tempIpAddress[i], tempRoadTrip[i], tempDescription[i], tempQualityHost[i]); //Thread.Sleep(4); } tempHostName.Clear(); tempIpAddress.Clear(); tempRoadTrip.Clear(); tempDescription.Clear(); tempQualityHost.Clear(); //Thread.Sleep(250); Console.ForegroundColor = ConsoleColor.White; } else { Console.ForegroundColor = ConsoleColor.Gray; Console.Clear(); Console.WriteLine(" \n \n \n \n \n \n Связи нет! \n ПРОВЕРЬТЕ СЕТЕВОЕ ПОДКЛЮЧЕНИЕ!pin"); } Console.WriteLine("\nКоличество итераций = " + iterator); Thread.Sleep(1500); } }
private void timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e) { //eventLog.WriteEntry("60 segundos..."); try { ClEnvioMail mail = new ClEnvioMail(); ClMonitoreo monitoreo = new ClMonitoreo(); TimeSpan Immalive = new TimeSpan(4, 0, 0); TimeSpan Ahora = new TimeSpan(DateTime.Now.Hour, DateTime.Now.Minute, 0); TimeSpan HoraProgramada = monitoreo.SeleccionHoraPeriodicidad(); if (Ahora == HoraProgramada) { string Serv = ""; string Serv1 = ""; DataTable Servidores = monitoreo.SeleccionServidoresMonitoreo(); for (int i = 0; i < Servidores.Rows.Count; i++) { if (Servidores.Rows[i]["ConsultarIP"].ToString().Trim().Equals("X")) { Serv = Servidores.Rows[i]["IP"].ToString().Trim(); Serv1 = Servidores.Rows[i]["Servidor"].ToString().Trim(); //Serv = Serv + " " + Servidores.Rows[i]["IP"].ToString().Trim(); } else { Serv = Servidores.Rows[i]["Servidor"].ToString().Trim(); Serv1 = Servidores.Rows[i]["Servidor"].ToString().Trim(); //Serv = Serv + " " + Servidores.Rows[i]["Servidor"].ToString().Trim(); } ManagementScope wmiScope = new ManagementScope(@"\\" + Serv + @"\root\cimv2"); ManagementObjectSearcher wmiSearcher = new ManagementObjectSearcher(wmiScope, new ObjectQuery(@"Select * from Win32_LogicalDisk WHERE DriveType=3")); string Body = ""; try { foreach (ManagementObject wmiObject in wmiSearcher.Get()) { try { string nombre = wmiObject["Name"].ToString().Substring(0, 1); double porcentajeFreeSpace = Math.Round((double)((double.Parse(wmiObject["FreeSpace"].ToString()) / double.Parse(wmiObject["Size"].ToString())) * 100), 2); double size = Math.Round(double.Parse(wmiObject["Size"].ToString()) / 1073741824, 2); double freeSpace = Math.Round(double.Parse(wmiObject["FreeSpace"].ToString()) / 1073741824, 2); double usedSpace = Math.Round((double.Parse(wmiObject["Size"].ToString()) - long.Parse(wmiObject["FreeSpace"].ToString())) / 1073741824, 2); //eventLog.WriteEntry(Serv + " " + nombre + " " + porcentajeFreeSpace.ToString() + " " + size.ToString() + " " + freeSpace.ToString() + " " + usedSpace.ToString()); //reviso si existe la tabla del servidor bool Existe = monitoreo.SelectTablaExiste(Serv1); if (!Existe) { //Si no existe la creo Existe = monitoreo.CreateTable(Serv1); } if (Existe) { monitoreo.InsertMonitoreo(Serv1, DateTime.Now, nombre, size, usedSpace, freeSpace, porcentajeFreeSpace); DataTable Alarmas = monitoreo.SelectParametrosAlertas(Serv1, nombre); //eventLog.WriteEntry("Alarmas: " + Alarmas.Rows.Count.ToString()); if (Alarmas.Rows.Count > 0) { //eventLog.WriteEntry("FreeSpace: " + freeSpace.ToString() + " Emergencia: " + Alarmas.Rows[0]["Emergencia"].ToString()); if (!(freeSpace > double.Parse(Alarmas.Rows[0]["Emergencia"].ToString()))) { //eventLog.WriteEntry("Emergencia"); Body = Body + "EMERGENCIA: \n"; Body = Body + " Disco: " + nombre + " \n"; Body = Body + " Espacio: " + size + "Gb \n"; Body = Body + " Utilizado: " + usedSpace + "Gb \n"; Body = Body + " Libre: " + freeSpace + "Gb \n"; Body = Body + " %Libre: " + porcentajeFreeSpace + "% \n\n"; } else { //eventLog.WriteEntry("FreeSpace: " + freeSpace.ToString() + " Alerta: " + Alarmas.Rows[0]["Alerta"].ToString()); if (!(freeSpace > double.Parse(Alarmas.Rows[0]["Alerta"].ToString()))) { //eventLog.WriteEntry("Alerta"); Body = Body + "ALERTA: \n"; Body = Body + " Disco: " + nombre + " \n"; Body = Body + " Espacio: " + size + "Gb \n"; Body = Body + " Utilizado: " + usedSpace + "Gb \n"; Body = Body + " Libre: " + freeSpace + "Gb \n"; Body = Body + " %Libre: " + porcentajeFreeSpace + "% \n\n"; } } } else { //Si no tiene alarmas inserto una monitoreo.InsertAlarma(Serv1, nombre, freeSpace - 1, freeSpace - 2); } } else { eventLog.WriteEntry("Error al crear tabla para datos de: " + Serv1); } } catch (Exception ex) { eventLog.WriteEntry("Error monitoreo: " + Serv + "---" + ex.Message); } } } catch (Exception ex) { if (ex.Message.Contains("El servidor RPC no está disponible.")) { try { Ping ping = new Ping(); PingReply pingR = ping.Send(Serv); if (pingR.Status == IPStatus.Success) { Body = Body + "ALERTA: \n"; Body = Body + " El servidor no está siendo monitoreado:\n"; Body = Body + " " + ex.Message; } else { Body = Body + "ALERTA: \n"; Body = Body + " El servidor no está disponible.\n\n"; } } catch { Body = Body + "ALERTA: \n"; Body = Body + " El servidor no está disponible.\n\n"; } } else { Body = Body + "ALERTA: \n"; Body = Body + " El servidor no está siendo monitoreado:\n"; Body = Body + " " + ex.Message; } } if (Body.Trim().Length > 0) { DataTable remitente = monitoreo.SelectRemitente(); DataTable destinatarios = monitoreo.SelectDestinatarios(Serv1); if (remitente.Rows.Count > 0) { if (destinatarios.Rows.Count > 0) { //eventLog.WriteEntry("Intenta enviar correo..."); if (!(mail.EnvioMail(remitente.Rows[0][0].ToString().Trim(), destinatarios, "ALERTA DISCOS: " + Serv1, Body))) { eventLog.WriteEntry("Error al enviar correo por monitoreo de discos."); } } } } } //eventLog.WriteEntry(Ahora.ToString() + " = " + HoraProgramada.ToString()); } else { if (Ahora == Immalive) { DataTable remitente = monitoreo.SelectRemitente(); DataTable destinatarios = monitoreo.SelectDestinatarios(""); if (remitente.Rows.Count > 0) { if (destinatarios.Rows.Count > 0) { //eventLog.WriteEntry("Intenta enviar correo..."); if (!(mail.EnvioMail(remitente.Rows[0][0].ToString().Trim(), destinatarios, "Up & Running", "El servicio de monitoreo de discos se esta ejecutando."))) { eventLog.WriteEntry("Error al enviar correo por monitoreo de discos."); } } } } } } catch (Exception ex) { eventLog.WriteEntry("Error monitoreo: " + ex.Message); } }
public void InputHostData()//переименуй процедуру { //вывод данных из файла на экран, пронумерованным списком for (bool check = true; check == true;) { command = Console.ReadLine(); switch (command) { //добавить редактирование данных по строке case "disp": try { displayFileData(); } catch (DirectoryNotFoundException) { Console.WriteLine("Файл отсутсвует"); } break; case "start": readFile(); check = false; break; case "add": enterByHand(); //ввод данных вручную readFile(); check = false; break; case "add -r": enterByHand(); //ввод данных вручную readFile(); check = false; break; case "add -b": enterByHand(); //ввод данных вручную readFile(); check = false; break; case "test": 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("10.10.10.10", 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); } else { 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); } reply = pingSender.Send("8.8.8.8", 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); } break; case "help": Console.WriteLine("Наберите команду для продолжения"); Console.WriteLine("disp - Вывести на экран содержимое файла \"HostDataBase.txt\""); Console.WriteLine("start - Запуск Пингера, по данным файла\"HostDataBase.txt\""); Console.WriteLine("add - для записи еще данных в конец файла, не стирая данные"); Console.WriteLine("add -r - для удаления данных из файла и записи их в ручную через консоль"); Console.WriteLine("add -b - будет сделан backup в \\%root_program_folder%\\Data\\backup\\%date%.txt"); break; default: Console.WriteLine("Команда введена не верно, повторите ввод \n"); break; } } }
//Scan Method public void Scan() { ActionButtonSwich(); /* Scan */ RTBClear(); //Source Address string SourceAddress = this.SourceText.Text; //Time Out int TimeOut = 0; Int32.TryParse(this.TimeOutText.Text, out TimeOut); if (this.TimeOutText.Text.Contains(' ')) { RTBAppendText("[Error] Invalid Timeout Expression!" + "\n", TextColors.Black); TimeOut = 0; /* Set to Default Timeout */ } if (TimeOut == 0) { TimeOut = 1000; RTBAppendText("Timeout Set to 1000ms (Default)" + " \n", TextColors.Black); RTBRefresh(); } else { RTBAppendText("Timeout Set to " + TimeOut.ToString() + "ms" + "\n", TextColors.Black); } //Destination Address string DestAddress = this.DestText.Text; //# Validation # bool SourceValidation = IPValidation(SourceAddress); bool DestValidation = IPValidation(DestAddress); if ((SourceValidation == false) || (DestValidation == false)) { RTBAppendText("Source Address: " + SourceAddress + "\n", TextColors.Black); RTBAppendText("Destination Address: " + DestAddress + "\n", TextColors.Black); RTBAppendText("[Error] Invalid Source or Destination Addresses!" + "\n", TextColors.Black); RTBRefresh(); } else { long SourceLong = Convert.ToInt64(SourceAddress.Replace(".", "")); long DestLong = Convert.ToInt64(DestAddress.Replace(".", "")); if (SourceLong >= DestLong) { RTBAppendText("Source Address: " + SourceAddress + "\n", TextColors.Black); RTBAppendText("Destination Address: " + DestAddress + "\n", TextColors.Black); RTBAppendText("[Error] Invalid IP Addresses Range!" + "\n", TextColors.Black); RTBRefresh(); } else { //Fix IP Address Format //Source string[] SourceSplit = SourceAddress.Split('.'); string SourceOctetOne = IPFixFormat(SourceSplit[0]); string SourceOctetTwo = IPFixFormat(SourceSplit[1]); string SourceOctetThree = IPFixFormat(SourceSplit[2]); string SourceOctetFour = IPFixFormat(SourceSplit[3]); SourceAddress = SourceOctetOne + "." + SourceOctetTwo + "." + SourceOctetThree + "." + SourceOctetFour; /* Modify Source Address */ System.Net.IPAddress SourceIP = System.Net.IPAddress.Parse(SourceAddress); /* Source IP */ //Destination string[] DestSplit = DestAddress.Split('.'); string DestOctetOne = IPFixFormat(DestSplit[0]); string DestOctetTwo = IPFixFormat(DestSplit[1]); string DestOctetThree = IPFixFormat(DestSplit[2]); string DestOctetFour = IPFixFormat(DestSplit[3]); DestAddress = DestOctetOne + "." + DestOctetTwo + "." + DestOctetThree + "." + DestOctetFour; /* Modify Destination Address */ System.Net.IPAddress DestIP = System.Net.IPAddress.Parse(DestAddress); /* Destination IP */ Byte[] SourceBytes = SourceIP.GetAddressBytes(); while (true) { SourceBytes[3] = (byte)(SourceBytes[3] + 1); /* 4th Octet */ if (SourceBytes[3] == 0) { SourceBytes[2] = (byte)(SourceBytes[2] + 1); /* 3rd Octet */ if (SourceBytes[2] == 0) { SourceBytes[1] = (byte)(SourceBytes[1] + 1); /* 2nd Octet */ if (SourceBytes[1] == 0) { SourceBytes[0] = (byte)(SourceBytes[0] + 1); /* 1st Octet */ } } } string CurrentAddress = SourceBytes[0].ToString() + "." + SourceBytes[1].ToString() + "." + SourceBytes[2].ToString() + "." + SourceBytes[3].ToString(); //Test Communication Ping Pinger = new Ping(); PingReply Reply = Pinger.Send(CurrentAddress, TimeOut); if (Reply.Status == IPStatus.Success) { RTBAppendText("[" + CurrentAddress + "]" + " Connection Established!" + "\n", TextColors.Green); } else { RTBAppendText("[" + CurrentAddress + "]" + " Device is Unavailable!" + "\n", TextColors.Red); } Pinger.Dispose(); RTBRefresh(); if (CurrentAddress == DestAddress) { break; /* Break Condition */ } } } } RTBAppendText("Finished!" + "\n", TextColors.Black); ActionButtonSwich(); /* Stop */ }
void TryDo(object device) { DeviceReal deviceReal = ((Device)device).DeviceReal; deviceReal.Error = "[no error]"; deviceReal.Done = false; deviceReal.Finished = false; try { Ping PingSender = new Ping(); PingOptions Options = new PingOptions(); byte[] buffer = Encoding.ASCII.GetBytes("a"); PingReply reply = PingSender.Send(deviceReal.IPAddress, 3000, buffer, Options); if (reply.Status == IPStatus.Success) { deviceReal.Pinged = true; deviceReal.ReplyTime = (int)reply.RoundtripTime; } else { deviceReal.Pinged = false; deviceReal.ReplyTime = -1; } if (deviceReal.Pinged) { RegistryObject SysRegistry = new RegistryRemote("karnaushenkosv", "qwert-+ZXCVB", "npr", deviceReal.IPAddress); deviceReal.WindowsVersion = SysRegistry.GetValue(baseKey.HKEY_LOCAL_MACHINE, @"SOFTWARE\Microsoft\Windows NT\CurrentVersion", "ProductName", valueType.STRING); ArrayList users = SysRegistry.EnumerateKeys(baseKey.HKEY_USERS, ""); Regex userReg = new Regex(@"\bS-\d{1,15}\-\d{1,15}\-\d{1,15}\-\d{1,15}-\d{1,15}-\d{1,15}-\d{1,15}\b"); ArrayList currentUsers = new ArrayList(); foreach (string user in users) { if (userReg.IsMatch(user)) { currentUsers.Add(user); } } if (currentUsers.Count > 0) { //deviceReal.UserName = SysRegistry.GetValue(baseKey.HKEY_USERS, string.Format(@"{0}\Volatile Environment", currentUser), "USERNAME", valueType.STRING); deviceReal.UserName = ""; foreach (string currentUser in currentUsers) { ArrayList keys = SysRegistry.EnumerateKeys(baseKey.HKEY_USERS, currentUser); if (keys.Contains("Volatile Environment")) { string temp = SysRegistry.GetValue(baseKey.HKEY_USERS, string.Format(@"{0}\Volatile Environment", currentUser), "HOMEPATH", valueType.STRING); temp = Path.GetFileNameWithoutExtension(temp); if (string.IsNullOrEmpty(deviceReal.UserName)) { deviceReal.UserName = temp; } else { deviceReal.UserName += string.Format(" || {0}", temp); } } } } UpdateWallpaper(deviceReal.IPAddress, deviceReal.WindowsVersion); deviceReal.Done = true; } } catch (Exception ex) { deviceReal.Error = string.Format("{0} -> {1}", ex.Source, ex.Message); } deviceReal.Finished = true; }
private void OnClickGo(object sender, EventArgs e) { _cancel = false; var server = textBoxServer.Text; var signalFile = textBoxInputFile.Text; var outputDir = textBoxOutputDir.Text; Ping ping = new Ping(); PingReply reply = ping.Send(server); if (reply.Status != IPStatus.Success) { if (MessageBox.Show(string.Format("Ping {0} failed, continue?", server), "Hmmm", MessageBoxButtons.YesNo) == DialogResult.No) { return; } } OnMessage(string.Format("Ping succeeded in: {0} ms", reply.RoundtripTime)); if (!File.Exists(signalFile)) { OnMessage("Signal file does not exist: " + signalFile); return; } try { if (!Directory.Exists(outputDir)) { Directory.CreateDirectory(outputDir); } } catch (Exception exception) { OnMessage(string.Format("Error creating directory {0}: {1}", outputDir, exception)); return; } int port; if (!TryGetPort(out port)) { OnMessage(string.Format("Can not get port: {0}", textBoxPort.Text)); return; } DateTime dtStartLocal = dateTimePickerStart.Value; DateTime dtEndLocal = dateTimePickerEnd.Value; if (dtStartLocal > DateTime.Now) { OnMessage("Start is later than now"); return; } if (dtStartLocal > dtEndLocal) { OnMessage("Start is later than end"); return; } SaveSettings(); buttonGo.Enabled = false; buttonCancel.Enabled = true; bool oneFile = checkBoxCombineCSVs.Checked; ThreadPool.QueueUserWorkItem(delegate { if (oneFile) { DateTime dtStartUTC = dtStartLocal.ToUniversalTime(); DateTime dtEndUTC = dtEndLocal.ToUniversalTime(); string outputFile = string.Format(@"{0} {1:yyyy_MM_dd HHmm} {2:yyyy_MM_dd HHmm}.csv", outputDir, dtStartUTC, dtEndUTC); ExportArrayOneFile(signalFile, dtStartLocal, dtEndLocal, server, port, outputFile); } else { ExportArrayIndividualFiles(signalFile, dtStartLocal, dtEndLocal, server, port, outputDir); } }); }
/// <summary> /// Creates a DBA Instance Parameter from the reply to a ping /// </summary> /// <param name="Ping">The result of a ping</param> public DbaInstanceParameter(PingReply Ping) { _ComputerName = Ping.Address.ToString(); }