Ejemplo n.º 1
0
 void Start()
 {
     client = new UdpClient(listenPort);
     client.Connect(scHostname,scPort);
     Send("/notify", 1);
     StartCoroutine( Listen() );
 }
Ejemplo n.º 2
0
    private void CreateConnection(NetworkOutboundDestination dest)
    {
        IPAddress ServerIP;
        int ServerPort; //Temporary

        switch (dest)
        {
            case NetworkOutboundDestination.LoginServer:
                //NetConnection = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
                ServerIP = IPAddress.Parse(GlobalValues.LOGIN_SERVER_IP);
                ServerPort = GlobalValues.LOGIN_PORT;
                break;
            case NetworkOutboundDestination.MainServer:
                //NetConnection = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
                ServerIP = IPAddress.Parse(GlobalValues.MAIN_SERVER_IP);
                ServerPort = GlobalValues.MAIN_PORT;
                break;
            default:
                throw new System.Exception("Attempting to create connection with non-existant server!");
        }

        currentConnectionEP = new IPEndPoint(ServerIP, ServerPort);

        sock = new UdpClient();
        sock.Connect(currentConnectionEP);
    }
Ejemplo n.º 3
0
    public static void Main()
    {
        string addr = "127.0.0.1";
        int port = 7980;
        short cmd = 1;
        short seq = 0;
        string msg = "Hello";
        byte[] payload = Encoding.ASCII.GetBytes(msg);
        byte[] packet = Packet.Create(cmd, seq, payload);

        UdpClient udp = new UdpClient();
        var ip = IPAddress.Parse(addr);
        IPEndPoint ep = new IPEndPoint(ip, port);
        udp.Connect(ep);

        // send
        udp.Send(packet, packet.Length);

        // receive
        bool done = false;
        while (!done) {
            if (udp.Available <= 0) {
                IPEndPoint ep2 = new IPEndPoint(0, 0);
                byte[] packet2 = udp.Receive(ref ep2);

                Console.WriteLine("packet size: {0}", packet2.Length);

                Dictionary<string, object> parsed = Packet.Parse(packet2);
                foreach (KeyValuePair<string, object> item in parsed) {
                    Console.WriteLine("Received:{0} = {1}", item.Key, item.Value);
                }
                done = true;
            }
        }
    }
Ejemplo n.º 4
0
    public bool Connect()
    {
        try
        {

            serverRemote = new IPEndPoint(IPAddress.Parse(ipAddress), portNumber);
            udpClient = new UdpClient();
            udpClient.Connect(serverRemote);
            if(udpClient.Client.Connected)
            {
                Debug.Log("connected!");
                sendUDPPacket("ANYONE OUT THERE?");

            //byte[] data = Encoding.UTF8.GetBytes(toSend);

            //client.Send(data, data.Length, serverRemote);
            //client.SendTimeout(serverRemote, data);

            }

        }
        catch(Exception ex)
        {
            print ( ex.Message + " : OnConnect");
        }
        isConnected = true;
        if ( udpClient == null ) return false;
        return udpClient.Client.Connected;
    }
Ejemplo n.º 5
0
 private static void StartListener()
 {
     bool done = false;
     IPEndPoint groupEP = new IPEndPoint(IPAddress.Any, listenPort);
     UdpClient listener = new UdpClient(groupEP);
     Log.Notice("Listener", "Waiting for broadcast");
     try
     {
         while (!done)
         {
             byte[] bytes = listener.Receive(ref groupEP);
             Log.Info("Listener", "Client " + groupEP.ToString() + " is trying to connect");
             listener.Connect(groupEP);
             Log.Succes("Listener", "Listener connected to client " + groupEP.ToString());
             done = true;
             //TODO - rest of district server connecting
         }
     }
     catch (Exception e)
     {
         FrameWork.Logger.Log.Error("Listener", e.ToString());
     }
     finally
     {
         listener.Close();
     }
 }
Ejemplo n.º 6
0
    public Backend(string ipAddress, int port)
    {
        // endpoint = new IPEndPoint(IPAddress.Parse(ipAddress), port);
        // this.EnableTimedTriggers();

        endpoint = new IPEndPoint(IPAddress.Parse(ipAddress), port);
        client = new UdpClient();
        client.Connect(endpoint);
        client.BeginReceive(new AsyncCallback(OnMessageRecieved), null);
    }
Ejemplo n.º 7
0
	public static void Main ()
	{
		var ip = IPAddress.Parse ("239.255.255.250");
		var bytes = new byte [] {60, 70, 75};
		UdpClient udp = new UdpClient ();
		udp.Connect (ip, 3802);
		udp.Send (bytes, 3);
		Console.WriteLine ("Sent");
		udp.Close ();
	}
Ejemplo n.º 8
0
    // Use this for initialization
    void Start()
    {
        udp = new UdpClient(port);
        udp.Client.ReceiveTimeout = 1000;

        udp.Connect(host, port);

        //thread = new Thread(new ThreadStart(Message));
        //thread.Start();
    }
Ejemplo n.º 9
0
    void Awake()
    {
        udpClient = new UdpClient(commandsPort);
        udpClient.Connect(IPAddress.Loopback, feedbackPort);

        // http://stackoverflow.com/a/7478498
        uint IOC_IN = 0x80000000;
        uint IOC_VENDOR = 0x18000000;
        uint SIO_UDP_CONNRESET = IOC_IN | IOC_VENDOR | 12;
        udpClient.Client.IOControl((int)SIO_UDP_CONNRESET, new byte[] { Convert.ToByte(false) }, null);
    }
Ejemplo n.º 10
0
    public void Init(string nothing)
    {
        remoteEndPoint = new IPEndPoint(IPAddress.Parse(remoteAddress), remotePort);
        timestamps = new Dictionary<string, Timestamp>();
        receivedMsgBuffer = new StringBuilder();
        completeMsgBuffer = new List<string>();

        try
        {
            TCPBuffer = new byte[1024];

            sendingUDPClient = new UdpClient();
            sendingUDPClient.ExclusiveAddressUse = false;
            sendingUDPClient.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
            sendingUDPClient.Connect(remoteAddress, remotePort);

            receivingUDPClient = new UdpClient();
            receivingUDPClient.ExclusiveAddressUse = false;
            receivingUDPClient.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
            receivingUDPClient.Client.Bind((IPEndPoint)sendingUDPClient.Client.LocalEndPoint);
            receivingUDPClient.Connect(remoteAddress, remotePort);
            receivingUDPClient.BeginReceive(new AsyncCallback(OnMessageUDP), null);

            // Send initial message to register the address and port at the server
            string hello = "Hello Server";
            byte[] bytes = Encoding.UTF8.GetBytes(hello);

            try
            {
                sendingUDPClient.Send(bytes, bytes.Length);
            }
            catch (Exception err)
            {
        #if !UNITY_EDITOR
                    Application.ExternalCall(onErrorCallback, "An error occurred while sending the initial message to the server: " + err.Message);
        #else
                    UnityEngine.Debug.LogError("An error occurred while sending the initial message to the server: " + err.Message);
        #endif
            }

            TCPClient = new TcpClient();
            TCPClient.NoDelay = true;
            TCPClient.Connect(remoteEndPoint);
            TCPClient.GetStream().BeginRead(TCPBuffer, 0, 1024, new AsyncCallback(OnMessageTCP), null);
        }
        catch (Exception err)
        {
        #if !UNITY_EDITOR
                Application.ExternalCall(onErrorCallback, err.ToString());
        #else
                UnityEngine.Debug.LogError("Init(): " + err.ToString());
        #endif
        }
    }
Ejemplo n.º 11
0
    void Awake()
    {
        DontDestroyOnLoad(transform.gameObject);

        //this.filePath = "port.txt";
        //loadPort();

        _broadcaster = new UdpClient();
        _broadcaster.EnableBroadcast = true;
        _broadcaster.Connect(new IPEndPoint(IPAddress.Broadcast, this.connectionPort));

        this.StartServer();
    }
Ejemplo n.º 12
0
        public FileSender(string ipAddress, int port, string fileName)
        {
            _fileName = fileName;

            _udpClient = new UdpClient(new Socket(AddressFamily.InterNetwork,
                SocketType.Dgram, ProtocolType.Udp));

            if (!_udpClient.Connect(ipAddress, port))
            {
                _udpClient.EndConnection();
                return;
            }

            SendingFileToServer();

            _udpClient.EndConnection();
        }
    public override bool Connect(string ip, int port)
    {
        if (_connected)
            Disconnect ();
        _addr.Address = IPAddress.Parse (ip);
        _addr.Port = port;

        try
        {
            _client = new UdpClient ();
            _client.Connect (_addr);
        }catch(Exception e)
        {
            LogSystem.Instance.Log("RemoteRobotCommunicator::Connect() - "+e.Message,LogSystem.LogType.Error);
        }

        _connected = true;
        return true;
    }
Ejemplo n.º 14
0
        /// <summary>
        /// 发送数据
        /// </summary>
        /// <param name="vData"></param>
        /// <param name="IsReturn"></param>
        /// <param name="WaiteTime"></param>
        /// <returns></returns>
        public bool SendData(ref byte[] vData, bool IsReturn, int WaiteTime)
        {
            try
            {
                lock (this)
                {
                    {
                        //Client = new UdpClient();
                        //Client.Client.Bind(this.localPoint);
                        if (Client == null || Client.Client == null)
                        {
                            Client = new UdpClient(UdpBindPort);
                        }
                    }
                }
                Client.Connect(Point);
            }
            catch (SocketException sex)
            {
                Console.WriteLine("UDPClient 136." + sex.Message + " " + localPoint + "." + sex.StackTrace);
                return(false);
            }
            Client.Send(vData, vData.Length);
            Console.WriteLine(UdpBindPort.ToString());
            Console.WriteLine("┏SendData:{0}", BitConverter.ToString(vData));
            if (!IsReturn)
            {
                Console.WriteLine("┗本包不需要回复");
                Client.Close();
                return(true);
            }
            Thread.Sleep(WaiteTime);
            byte[]      BytReceived = new byte[0];
            bool        IsReveive   = false;             //标志是否返回
            List <byte> RevItems    = new List <byte>(); //接收的数据集合
            DateTime    Dt;                              //等待时间变量

            Dt = DateTime.Now;
            while (TimeSub(DateTime.Now, Dt) < MaxWaitSeconds)
            {
                Thread.Sleep(1);
                try
                {
                    if (Client.Available > 0)
                    {
                        BytReceived = Client.Receive(ref Point);
                        IsReveive   = true;
                        break;
                    }
                }
                catch
                {
                    Client.Close();
                    return(false);
                }
            }

            if (!IsReveive)
            {
                vData = new byte[0];
            }
            else
            {
                RevItems.AddRange(BytReceived);
                Dt = DateTime.Now;
                while (TimeSub(DateTime.Now, Dt) < WaitSecondsPerByte)
                {
                    if (Client.Available > 0)
                    {
                        BytReceived = Client.Receive(ref Point);
                        RevItems.AddRange(BytReceived);
                        Dt = DateTime.Now;
                    }
                }
                vData = RevItems.ToArray();
            }
            Console.WriteLine("┗RecvData:{0}", BitConverter.ToString(vData));
            Client.Close();
            return(true);
        }
Ejemplo n.º 15
0
        public QueryData Querying(string targetIP, int targetPort)
        {
            bool isExceptionOccured = false;

            byte[] info = { }, challenge = { }, player = { };
            string log  = string.Empty;

            try
            {
                udpClient = new UdpClient();
                endPoint  = new IPEndPoint(IPAddress.Parse(targetIP), targetPort);
                udpClient.Client.SendTimeout    = 5000;
                udpClient.Client.ReceiveTimeout = 5000;

                udpClient.Connect(endPoint);

                log += "UDPCLIENT : Connected\n";
            }
            catch (Exception)
            {
                isExceptionOccured = true;
                log += "UDPCLIENT : Connection failed\n";
            }

            // request challenge code
            try
            {
                udpClient.Send(new byte[] {
                    0xFF, 0xFF, 0xFF, 0xFF
                    , HEADER_PLAYER
                    , 0xFF, 0xFF, 0xFF, 0xFF
                }, 9);
                challenge = udpClient.Receive(ref endPoint);

                log += "UDPCLIENT : Server response to request (A2S_CHALLENGE)\n";
            }
            catch (Exception)
            {
                isExceptionOccured = true;
                log += "UDPCLIENT : Failed to request A2S_CHALLENGE\n";
            }

            // request player list
            try
            {
                udpClient.Send(new byte[] { 0xFF, 0xFF, 0xFF, 0xFF
                                            , HEADER_PLAYER
                                            , challenge[5], challenge[6], challenge[7], challenge[8] }, 9);
                player = udpClient.Receive(ref endPoint);

                log += "UDPCLIENT : Server response to request (A2S_PLAYER)\n";
            }
            catch (Exception)
            {
                isExceptionOccured = true;
                log += "UDPCLIENT : Failed to request A2S_PLAYER\n";
            }

            // request server information
            try
            {
                udpClient.Send(new byte[] {
                    0xFF, 0xFF, 0xFF, 0xFF, HEADER_INFO,
                    0x53, 0x6F, 0x75, 0x72, 0x63,
                    0x65, 0x20, 0x45, 0x6E, 0x67,
                    0x69, 0x6E, 0x65, 0x20, 0x51,
                    0x75, 0x65, 0x72, 0x79, 0x00
                }, 25);
                info = udpClient.Receive(ref endPoint);

                log += "UDPCLIENT : Server response to request (A2S_INFO)\n";
            }
            catch (Exception)
            {
                isExceptionOccured = true;
                log += "UDPCLIENT : Failed to request A2S_INFO\n";
            }

            if (isExceptionOccured == true)
            {
                throw new Exception();
            }

            return(new QueryData(challenge, player, info, log));
        }
Ejemplo n.º 16
0
 public void StartStreaming()
 {
     udpSender = new UdpClient();
     udpSender.Connect(serverEndpoint);
     Streaming = true;
 }
Ejemplo n.º 17
0
    private void ReceiveData()
    {
        home = new IPEndPoint(IPAddress.Parse(addr),port);
        client = new UdpClient ();
        //client.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
        //IPEndPoint treadmillIP = new IPEndPoint(1020014833,0);

        try
        {

            client.Connect("treadmill-OptiPlex-980",27015);
            //client.Connect("Windsor",27015);
            byte[] sendBytes = Encoding.UTF8.GetBytes("Send Patch Array");
            client.Send(sendBytes, sendBytes.Length);
            byte[] data = client.Receive(ref home);
            string text = Encoding.UTF8.GetString(data);
            print(text);
            patchArray = intParser(text);

            sendBytes = Encoding.UTF8.GetBytes("Send Patch Type Array");
            client.Send(sendBytes, sendBytes.Length);

            data = client.Receive(ref home);
            text = Encoding.UTF8.GetString(data);
            print(text);
            patchTypes = intParser(text);
            print("parsed patch types");
        }

        catch (Exception err)
        {
            print (err.ToString());
        }

        while(running)
        {

            try
            {
                // Send distance to next patch
                string distanceStr = distanceToNext.ToString();
                byte[] sendBytes = Encoding.UTF8.GetBytes(distanceStr);
                client.Send(sendBytes, sendBytes.Length);

                // Get joint angles
                byte[] angleData = client.Receive(ref home);
                string angleStr = Encoding.UTF8.GetString(angleData);
                angles = doubleParser (angleStr);

                // Check if next step will be stiffness change
                byte[] pertData = client.Receive(ref home);
                pertStatus = Convert.ToInt32(Encoding.UTF8.GetString(pertData));

                byte[] speedData = client.Receive(ref home);
                treadmillSpeed = Convert.ToSingle(Encoding.UTF8.GetString(speedData));
            }
            catch(SocketException err)
            {
                print(err.ToString());
            }

            catch(ObjectDisposedException err)
            {
                print(err.ToString());
                running = false;
            }

        }
    }
Ejemplo n.º 18
0
 public Form1()
 {
     InitializeComponent();
     outSocket.Connect(serverEndPoint);
     Start();
 }
Ejemplo n.º 19
0
        static void Main(string[] args)
        {
            //Console.WindowWidth = 120;
            //Console.WindowHeight = 76;

            X509KeyStorageFlags flags = X509KeyStorageFlags.Exportable;
            X509Certificate2    cert  = new X509Certificate2("cert_key.p12", "1234", flags);
            X509Certificate2    certp = new X509Certificate2("public.cer");

            byte[] key = new byte[16];

            //lettura chiave privata
            rsa = (RSACryptoServiceProvider)cert.PrivateKey;

            //esporta i parametri della chiave privata
            privateParam = rsa.ExportParameters(true);

            //lettura chiave pubblica
            rsa = (RSACryptoServiceProvider)certp.PublicKey.Key;

            //esporta i parametri della chiave pubblica
            publicParam = rsa.ExportParameters(false);

            //fornisce l'interfaccia di comunicazione
            UdpClient client = new UdpClient();

            //crea l'ipendpoint in locale
            IPEndPoint ipep = new IPEndPoint(IPAddress.Parse("127.0.0.1"), port);

            //connessione all'endpoint
            client.Connect(ipep);

            //client status
            int cs = 0;

            while (cs < 3)
            {
                switch (cs)
                {
                case 0:
                {
                    Console.Write("Push any key to connect with the server: ");

                    //legge la stringa da tastiera e la converte in byte
                    byte[] packet = Encoding.ASCII.GetBytes(Console.ReadLine());
                    client.Send(packet, packet.Length);

                    //si mette in ascolto
                    var data = client.Receive(ref ipep);
                    Console.Write(Encoding.ASCII.GetString(data));

                    //invio del certificato
                    byte[] certData = cert.Export(X509ContentType.Cert);
                    client.Send(certData, certData.Length);

                    //riceve certificato
                    byte[]           certReceived = client.Receive(ref ipep);
                    X509Certificate2 serverCert   = new X509Certificate2(certReceived);

                    string resultTrue = serverCert.ToString(true);

                    Console.WriteLine("\nServer's certificate received:\n" + resultTrue);

                    Console.WriteLine("/**********************************************************************************************************************/");

                    rsa_server = (RSACryptoServiceProvider)serverCert.PublicKey.Key;

                    //riceve la chiave simmetrica
                    byte[] encryptedKey = client.Receive(ref ipep);

                    //decritta la chiave con la propria chiave privata
                    rsa.ImportParameters(privateParam);
                    key = rsa.Decrypt(encryptedKey, false);

                    Console.WriteLine("Simmetric Key = " + new UnicodeEncoding().GetString(key));

                    //riceve il modulo e la base da utilizzare
                    byte[] values = client.Receive(ref ipep);

                    module = values[0];
                    g      = values[1];

                    cs++;
                    break;
                }

                case 1:
                {
                    Console.WriteLine("Base = " + g);
                    Console.WriteLine("Module = " + module);

                    //riceve gx crittato
                    byte[] encrypt_gx = client.Receive(ref ipep);

                    //decritta gx
                    rsa.ImportParameters(privateParam);
                    byte[] decrypt_gx = rsa.Decrypt(encrypt_gx, true);

                    //converte gx in intero
                    int gx = Int32.Parse(Encoding.ASCII.GetString(decrypt_gx));

                    Console.WriteLine("g^x mod p = " + gx);

                    int expo = rnd.Next(2, 9);
                    Console.WriteLine("Exponent y = " + expo);

                    //calcola g^y mod p
                    int gy = (int)BigInteger.ModPow(g, expo, module);
                    Console.WriteLine("g^y mod p = " + gy);

                    //critta g^y
                    byte[] encrypt_gy = rsa_server.Encrypt(Encoding.ASCII.GetBytes(gy.ToString()), true);

                    //calcola k = (g^x)^y
                    secret = (int)BigInteger.ModPow(gx, expo, module);
                    Console.WriteLine("Secret(k) = " + secret + "\n");

                    Console.WriteLine("/*********************************************************************************************End of parameters********/");

                    //firma il valore hash di k + gx + gy con chiave privata
                    string signedHash = signMessage(secret + gx + gy.ToString(), privateParam);

                    //cifra con chiave simmetrica il valore di hash firmato
                    byte[] signed_BHash = Aes_encrypt(signedHash, key);

                    //invia hash firmato
                    client.Send(signed_BHash, signed_BHash.Length);

                    //invia g^y crittato con chiave pubblica
                    client.Send(encrypt_gy, encrypt_gy.Length);

                    //riceve pacchetto di autenticazione firmato dal server
                    byte[] revSignHash = client.Receive(ref ipep);

                    //decritta il pacchetto
                    string revSignature = Aes_decrypt(revSignHash, key);

                    //verifica dell'hash code
                    if (verifySignature(secret + gy + gx.ToString(), revSignature, publicParam))
                    {
                        Console.WriteLine("<SERVER:> " + "authentication failed, permissions are denied !");
                        Console.WriteLine("<SERVER:> the connection will be rejected, press a key to end");
                        Console.ReadKey();
                        Environment.Exit(0);
                    }

                    else
                    {
                        Console.WriteLine("\n<SERVER:> authentication performed successfully !");
                        Console.WriteLine("<SERVER:> a secret key has been mutually authenticated and validated !\n");
                    }

                    cs++;
                    break;
                }

                case 2:
                {
                    byte[] Btoken = client.Receive(ref ipep);

                    string token = new UnicodeEncoding().GetString(Btoken);

                    Console.WriteLine("Session token: " + token + "\n");

                    Console.Write("Write message: ");

                    //legge la stringa da tastiera e la converte in byte
                    byte[] data = new UnicodeEncoding().GetBytes("<cute girl:> " + Console.ReadLine());

                    //firma della sessione
                    byte[] digest = new UnicodeEncoding().GetBytes(signMessage(data.Length + token + secret, privateParam));

                    //creazione del pacchetto da inviare
                    byte[] sendPacket = new byte[digest.Length + data.Length];
                    System.Buffer.BlockCopy(digest, 0, sendPacket, 0, digest.Length);
                    System.Buffer.BlockCopy(data, 0, sendPacket, digest.Length, data.Length);

                    client.Send(sendPacket, sendPacket.Length);

                    byte[] response = client.Receive(ref ipep);

                    Console.WriteLine(new UnicodeEncoding().GetString(response));

                    if (new UnicodeEncoding().GetString(data).Equals("<cute girl:> " + "bye"))
                    {
                        cs++;
                    }

                    break;
                }
                }
            }
        }
Ejemplo n.º 20
0
        private void button1_Click(object sender, EventArgs e)
        {
            client.Connect(new IPEndPoint(IPAddress.Parse("127.0.0.1"), 8080));

            byte[] sendr = Encoding.UTF8.GetBytes(RSAEncrypt(User.Text) + "," + RSAEncrypt(pass.Text));
            client.Send(sendr, sendr.Length);
            Console.WriteLine("Done Message sent by client");

            byte[] bx      = client.Receive(ref groupEP);
            string decider = Encoding.UTF8.GetString(bx);

            Console.WriteLine("Okay Server" + decider);
            string[] logintokens = decider.Split(',');
            string   loginer1 = "", loginer2 = "", loginer3 = "";

            for (int i = 0; i < logintokens.Length; i++)
            {
                if (i == 0)
                {
                    loginer1 = logintokens[i];
                }
                if (i == 1)
                {
                    loginer2 = logintokens[i];
                }
                if (i == 2)
                {
                    loginer3 = logintokens[i];
                }
            }
            if (loginer1.Equals("1"))
            {
                String decryptedText = new HarshSign().ExtractMessage(loginer2, loginer3);
                Console.WriteLine(decryptedText);
                String [] textChanger = decryptedText.Split(',');
                string    a1 = "", a2 = "", a3 = "", a4 = "";
                for (int i = 0; i < textChanger.Length; i++)
                {
                    if (i == 0)
                    {
                        a1 = textChanger[i];
                    }
                    if (i == 1)
                    {
                        a2 = textChanger[i];
                    }
                    if (i == 2)
                    {
                        a3 = textChanger[i];
                    }
                    if (i == 3)
                    {
                        a4 = textChanger[i];
                    }
                }
                li.Show(); ly.Show(); lm.Show(); le.Show();
                I.Show(); m.Show(); y.Show(); eu.Show();
                m.Text  = a1;
                y.Text  = a2;
                eu.Text = a3;
                I.Text  = a4;
                MessageBox.Show(decryptedText);
            }
            else if (loginer1.Equals("0"))
            {
                Console.WriteLine("Error logging you in");
                MessageBox.Show("Error:- Logging you in ");
            }
            else
            {
            }
        }
Ejemplo n.º 21
0
 protected override void Connect()
 {
     _client.Connect(new IPEndPoint(Host, Port));
 }
Ejemplo n.º 22
0
        public static void MDNSListener(string IP, string spooferIP, string mdnsTTL, string[] mdnsTypes)
        {
            byte[] spooferIPData = IPAddress.Parse(spooferIP).GetAddressBytes();
            byte[] ttlMDNS       = BitConverter.GetBytes(Int32.Parse(mdnsTTL));
            Array.Reverse(ttlMDNS);
            IPEndPoint mdnsEndpoint = new IPEndPoint(IPAddress.Any, 5353);
            UdpClient  mdnsClient   = new UdpClient();

            try
            {
                mdnsClient.ExclusiveAddressUse = false;
                mdnsClient.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
                mdnsClient.Client.Bind(mdnsEndpoint);
                mdnsClient.JoinMulticastGroup(IPAddress.Parse("224.0.0.251"));
            }
            catch
            {
                lock (Program.outputList)
                {
                    Program.outputList.Add(String.Format("[-] Error starting unprivileged mDNS spoofer, UDP port sharing does not work on all versions of Windows.", DateTime.Now.ToString("s")));
                }

                throw;
            }

            while (!Program.exitInveigh)
            {
                try
                {
                    string    mdnsResponseMessage = "";
                    byte[]    udpPayload          = mdnsClient.Receive(ref mdnsEndpoint);
                    int       mdnsSourcePort      = mdnsEndpoint.Port;
                    byte[]    mdnsType            = new byte[2];
                    IPAddress sourceIPAddress     = mdnsEndpoint.Address;

                    if (BitConverter.ToString(udpPayload).EndsWith("-00-01-80-01") && String.Equals(BitConverter.ToString(udpPayload).Substring(12, 23), "00-01-00-00-00-00-00-00"))
                    {
                        byte[] mdnsTransactionID   = new byte[2];
                        string mdnsRequestHostFull = Util.ParseNameQuery(12, udpPayload);
                        System.Buffer.BlockCopy(udpPayload, 0, mdnsTransactionID, 0, 2);
                        byte[] mdnsRequest = new byte[mdnsRequestHostFull.Length + 2];
                        System.Buffer.BlockCopy(udpPayload, 12, mdnsRequest, 0, mdnsRequest.Length);
                        string[] mdnsRequestSplit = mdnsRequestHostFull.Split('.');

                        if (mdnsRequestSplit != null && mdnsRequestSplit.Length > 0)
                        {
                            mdnsResponseMessage = Util.CheckRequest(mdnsRequestSplit[0], sourceIPAddress.ToString(), IP.ToString(), "MDNS");
                        }

                        if (Program.enabledMDNS && String.Equals(mdnsResponseMessage, "response sent"))
                        {
                            using (MemoryStream ms = new MemoryStream())
                            {
                                ms.Write(mdnsTransactionID, 0, mdnsTransactionID.Length);
                                ms.Write((new byte[10] {
                                    0x84, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00
                                }), 0, 10);
                                ms.Write(mdnsRequest, 0, mdnsRequest.Length);
                                ms.Write((new byte[4] {
                                    0x00, 0x01, 0x80, 0x01
                                }), 0, 4);
                                ms.Write(ttlMDNS, 0, 4);
                                ms.Write((new byte[2] {
                                    0x00, 0x04
                                }), 0, 2);
                                ms.Write(spooferIPData, 0, spooferIPData.Length);
                                IPEndPoint mdnsDestinationEndPoint = new IPEndPoint(sourceIPAddress, mdnsSourcePort);
                                mdnsClient.Connect(mdnsDestinationEndPoint);
                                mdnsClient.Send(ms.ToArray(), ms.ToArray().Length);
                                mdnsClient.Close();
                                mdnsEndpoint = new IPEndPoint(IPAddress.Any, 5353);
                                mdnsClient   = new UdpClient();
                                mdnsClient.ExclusiveAddressUse = false;
                                mdnsClient.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
                                mdnsClient.Client.Bind(mdnsEndpoint);
                                mdnsClient.JoinMulticastGroup(IPAddress.Parse("224.0.0.251"));
                            }
                        }

                        lock (Program.outputList)
                        {
                            Program.outputList.Add(String.Format("[+] [{0}] mDNS(QU) request for {1} received from {2} [{3}]", DateTime.Now.ToString("s"), mdnsRequestHostFull, sourceIPAddress, mdnsResponseMessage));
                        }
                    }
                    else if (BitConverter.ToString(udpPayload).EndsWith("-00-01") && (String.Equals(BitConverter.ToString(udpPayload).Substring(12, 23), "00-01-00-00-00-00-00-00") ||
                                                                                      String.Equals(BitConverter.ToString(udpPayload).Substring(12, 23), "00-02-00-00-00-00-00-00")))
                    {
                        byte[] mdnsTransactionID = new byte[2];
                        System.Buffer.BlockCopy(udpPayload, 0, mdnsTransactionID, 0, 2);
                        string mdnsRequestHostFull = Util.ParseNameQuery(12, udpPayload);
                        byte[] mdnsRequest         = new byte[mdnsRequestHostFull.Length + 2];
                        System.Buffer.BlockCopy(udpPayload, 12, mdnsRequest, 0, mdnsRequest.Length);
                        string[] mdnsRequestSplit = mdnsRequestHostFull.Split('.');

                        if (mdnsRequestSplit != null && mdnsRequestSplit.Length > 0)
                        {
                            mdnsResponseMessage = Util.CheckRequest(mdnsRequestSplit[0], sourceIPAddress.ToString(), IP.ToString(), "MDNS");
                        }

                        if (Program.enabledMDNS && String.Equals(mdnsResponseMessage, "response sent"))
                        {
                            if (Array.Exists(mdnsTypes, element => element == "QM"))
                            {
                                using (MemoryStream ms = new MemoryStream())
                                {
                                    ms.Write(mdnsTransactionID, 0, mdnsTransactionID.Length);
                                    ms.Write((new byte[10] {
                                        0x84, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00
                                    }), 0, 10);
                                    ms.Write(mdnsRequest, 0, mdnsRequest.Length);
                                    ms.Write((new byte[4] {
                                        0x00, 0x01, 0x80, 0x01
                                    }), 0, 4);
                                    ms.Write(ttlMDNS, 0, 4);
                                    ms.Write((new byte[2] {
                                        0x00, 0x04
                                    }), 0, 2);
                                    ms.Write(spooferIPData, 0, spooferIPData.Length);
                                    IPEndPoint mdnsDestinationEndPoint = new IPEndPoint(IPAddress.Parse("224.0.0.251"), 5353);
                                    mdnsClient.Connect(mdnsDestinationEndPoint);
                                    mdnsClient.Send(ms.ToArray(), ms.ToArray().Length);
                                    mdnsClient.Close();
                                    mdnsEndpoint = new IPEndPoint(IPAddress.Any, 5353);
                                    mdnsClient   = new UdpClient();
                                    mdnsClient.ExclusiveAddressUse = false;
                                    mdnsClient.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
                                    mdnsClient.Client.Bind(mdnsEndpoint);
                                    mdnsClient.JoinMulticastGroup(IPAddress.Parse("224.0.0.251"));
                                }
                            }
                            else
                            {
                                mdnsResponseMessage = "mDNS type disabled";
                            }
                        }

                        lock (Program.outputList)
                        {
                            Program.outputList.Add(String.Format("[+] [{0}] mDNS(QM) request for {1} received from {2} [{3}]", DateTime.Now.ToString("s"), mdnsRequestHostFull, sourceIPAddress, mdnsResponseMessage));
                        }
                    }
                }
                catch (Exception ex)
                {
                    Program.outputList.Add(String.Format("[-] [{0}] mDNS spoofer error detected - {1}", DateTime.Now.ToString("s"), ex.ToString()));
                }
            }
        }
Ejemplo n.º 23
0
        public static void NBNSListener(string IP, string spooferIP, string nbnsTTL, string[] nbnsTypes)
        {
            byte[] spooferIPData = IPAddress.Parse(spooferIP).GetAddressBytes();
            byte[] ttlNBNS       = BitConverter.GetBytes(Int32.Parse(nbnsTTL));
            Array.Reverse(ttlNBNS);
            IPEndPoint nbnsEndpoint = new IPEndPoint(IPAddress.Broadcast, 137);
            UdpClient  nbnsClient;

            try
            {
                nbnsClient = new UdpClient(137);
            }
            catch
            {
                lock (Program.outputList)
                {
                    Program.outputList.Add(String.Format("[-] Error starting unprivileged NBNS spoofer, UDP port sharing does not work on all versions of Windows.", DateTime.Now.ToString("s")));
                }

                throw;
            }

            while (!Program.exitInveigh)
            {
                try
                {
                    byte[] udpPayload             = nbnsClient.Receive(ref nbnsEndpoint);
                    byte[] nbnsQuestionsAnswerRRs = new byte[4];
                    System.Buffer.BlockCopy(udpPayload, 4, nbnsQuestionsAnswerRRs, 0, 4);
                    byte[] nbnsAdditionalRRs = new byte[2];
                    System.Buffer.BlockCopy(udpPayload, 10, nbnsAdditionalRRs, 0, 2);

                    if (BitConverter.ToString(nbnsQuestionsAnswerRRs) == "00-01-00-00" && BitConverter.ToString(nbnsAdditionalRRs) != "00-01")
                    {
                        string nbnsResponseMessage = "";
                        byte[] nbnsTransactionID   = new byte[2];
                        System.Buffer.BlockCopy(udpPayload, 0, nbnsTransactionID, 0, 2);
                        byte[] nbnsRequestType = new byte[2];
                        System.Buffer.BlockCopy(udpPayload, 43, nbnsRequestType, 0, 2);
                        string nbnsQueryType = NBNSQueryType(nbnsRequestType);
                        byte[] nbnsType      = new byte[1];
                        System.Buffer.BlockCopy(udpPayload, 47, nbnsType, 0, 1);
                        byte[] nbnsRequest = new byte[udpPayload.Length - 20];
                        System.Buffer.BlockCopy(udpPayload, 13, nbnsRequest, 0, nbnsRequest.Length);
                        string    nbnsRequestHost = BytesToNBNSQuery(nbnsRequest);
                        IPAddress sourceIPAddress = nbnsEndpoint.Address;
                        nbnsResponseMessage = Util.CheckRequest(nbnsRequestHost, sourceIPAddress.ToString(), IP.ToString(), "NBNS");

                        if (Program.enabledNBNS && String.Equals(nbnsResponseMessage, "response sent"))
                        {
                            if (Array.Exists(nbnsTypes, element => element == nbnsQueryType) && !String.Equals(BitConverter.ToString(nbnsType), "21"))
                            {
                                using (MemoryStream ms = new MemoryStream())
                                {
                                    ms.Write(nbnsTransactionID, 0, nbnsTransactionID.Length);
                                    ms.Write((new byte[11] {
                                        0x85, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x20
                                    }), 0, 11);
                                    ms.Write(nbnsRequest, 0, nbnsRequest.Length);
                                    ms.Write(nbnsRequestType, 0, 2);
                                    ms.Write((new byte[5] {
                                        0x00, 0x00, 0x20, 0x00, 0x01
                                    }), 0, 5);
                                    ms.Write(ttlNBNS, 0, 4);
                                    ms.Write((new byte[4] {
                                        0x00, 0x06, 0x00, 0x00
                                    }), 0, 4);
                                    ms.Write(spooferIPData, 0, spooferIPData.Length);
                                    IPEndPoint nbnsDestinationEndPoint = new IPEndPoint(sourceIPAddress, 137);
                                    nbnsClient.Connect(nbnsDestinationEndPoint);
                                    nbnsClient.Send(ms.ToArray(), ms.ToArray().Length);
                                    nbnsClient.Close();
                                    nbnsClient = new UdpClient(137);
                                }
                            }
                            else if (String.Equals(BitConverter.ToString(nbnsType), "21"))
                            {
                                nbnsResponseMessage = "NBSTAT request";
                            }
                            else
                            {
                                nbnsResponseMessage = "NBNS type disabled";
                            }
                        }

                        lock (Program.outputList)
                        {
                            Program.outputList.Add(String.Format("[+] [{0}] NBNS request for {1}<{2}> received from {3} [{4}]", DateTime.Now.ToString("s"), nbnsRequestHost, nbnsQueryType, sourceIPAddress, nbnsResponseMessage));
                        }
                    }
                }
                catch (Exception ex)
                {
                    Program.outputList.Add(String.Format("[-] [{0}] NBNS spoofer error detected - {1}", DateTime.Now.ToString("s"), ex.ToString()));
                }
            }
        }
Ejemplo n.º 24
0
 public void Init(string ip = "127.0.0.1", int port = 60000)
 {
     client = new UdpClient();
     client.Connect(ip, port);
     client.BeginReceive(Receive, client);
 }
Ejemplo n.º 25
0
        public IModbusMaster Create()
        {
            var factory = new ModbusFactory();

            switch (_connection.Type)
            {
            case ConnectionType.Rtu:
            {
                var serialPort = CreateAndOpenSerialPort(_connection);

                var transport = new SerialPortAdapter(serialPort);

                return(factory.CreateRtuMaster(transport));
            }

            case ConnectionType.Ascii:
            {
                var serialPort = CreateAndOpenSerialPort(_connection);

                var transport = new SerialPortAdapter(serialPort);

                return(factory.CreateRtuMaster(transport));
            }

            case ConnectionType.Tcp:
            {
                var tcpClient = new TcpClient
                {
                    ReceiveTimeout = _connection.ReadTimeout,
                    SendTimeout    = _connection.WriteTimeout
                };

                var effectiveConnectionTimeout = _connection.ConnectionTimeout;

                if (effectiveConnectionTimeout <= 0)
                {
                    effectiveConnectionTimeout = DefaultTcpConnectionTimeoutMilliseconds;
                }

                if (!tcpClient.ConnectAsync(_connection.HostName, _connection.Port).Wait(effectiveConnectionTimeout))
                {
                    tcpClient.Dispose();

                    throw new TimeoutException($"Timed out trying to connect to TCP Modbus device at {_connection.HostName}:{_connection.Port}");
                }

                return(factory.CreateMaster(tcpClient));
            }

            case ConnectionType.Udp:
            {
                var udpClient = new UdpClient();

                udpClient.Client.ReceiveTimeout = _connection.ReadTimeout;
                udpClient.Client.SendTimeout    = _connection.WriteTimeout;

                udpClient.Connect(_connection.HostName, _connection.Port);

                return(factory.CreateMaster(udpClient));
            }

            default:
                throw new ArgumentException($"{nameof(_connection.Type)} had an unepected value '{_connection.Type}'.");
            }
        }
Ejemplo n.º 26
0
        /// <summary>
        /// Gateway lobby logic is done on a separate thread so that it's not blocking the main thread.
        /// </summary>

        void ThreadDiscover(object obj)
        {
            Thread th = (Thread)obj;

            string request = "M-SEARCH * HTTP/1.1\r\n" +
                             "HOST: 239.255.255.250:1900\r\n" +
                             "ST:upnp:rootdevice\r\n" +
                             "MAN:\"ssdp:discover\"\r\n" +
                             "MX:3\r\n\r\n";

            byte[]           requestBytes = Encoding.ASCII.GetBytes(request);
            int              port         = 10000 + (int)(DateTime.UtcNow.Ticks % 45000);
            List <IPAddress> ips          = Tools.localAddresses;

            // UPnP discovery should happen on all network interfaces
            for (int i = 0; i < ips.size; ++i)
            {
                IPAddress ip = ips[i];
                mStatus = Status.Searching;
                UdpClient receiver = null;

                try
                {
                    UdpClient sender = new UdpClient(new IPEndPoint(ip, port));

                    sender.Connect(IPAddress.Broadcast, 1900);
                    sender.Send(requestBytes, requestBytes.Length);
                    sender.Close();

                    receiver = new UdpClient(new IPEndPoint(ip, port));
                    receiver.Client.ReceiveTimeout = 3000;

                    IPEndPoint sourceAddress = new IPEndPoint(IPAddress.Any, 0);

                    for (; ;)
                    {
                        byte[] data = receiver.Receive(ref sourceAddress);

                        if (ParseResponse(Encoding.ASCII.GetString(data, 0, data.Length)))
                        {
                            receiver.Close();

                            lock (mThreads)
                            {
                                mGatewayAddress = sourceAddress.Address;
#if UNITY_EDITOR
                                UnityEngine.Debug.Log("[TNet] UPnP Gateway: " + mGatewayAddress);
#endif
                                mStatus = Status.Success;
                                mThreads.Remove(th);
                            }
                            mDiscover = null;
                            return;
                        }
                    }
                }
                catch (System.Exception) {}

                if (receiver != null)
                {
                    receiver.Close();
                }

                lock (mThreads)
                {
                    mStatus = Status.Failure;
                    mThreads.Remove(th);
                }
                mDiscover = null;

                // If we found one, we're done
                if (mStatus == Status.Success)
                {
                    break;
                }
            }

            if (mStatus != Status.Success)
            {
#if UNITY_EDITOR
                UnityEngine.Debug.LogWarning("[TNet] UPnP discovery failed. TNet won't be able to open ports automatically.");
#else
                Console.WriteLine("UPnP discovery failed. TNet won't be able to open ports automatically.");
#endif
            }
        }
Ejemplo n.º 27
0
    void Start()
    {
        Debug.Log ("Initializing Client");
        objs = new Dictionary<string, Tracker_Obj>();
        serialized_objs = new List<Tracker_Obj>();

        // Servers recieve messages
        // Clients send messages

        client = null;
        try { client = new UdpClient(42069); }
        catch (Exception e) { Console.WriteLine(e.ToString()); return;}

        Debug.Log ("Requesting Tracker Access");
        ep = new IPEndPoint(IPAddress.Parse("129.161.12.88"), 42068);
        client.Connect(ep);

        byte[] msg = System.Text.Encoding.UTF8.GetBytes("ADD ME");
        client.Send(msg, msg.Length);

        #if UNITY_EDITOR
        EditorApplication.update += Update;
        #endif
    }
Ejemplo n.º 28
0
        static void Main(string[] args)
        {
            //tells the system to only use available processor cycles allowing the program to run in the background
            System.Diagnostics.Process.GetCurrentProcess().PriorityClass = System.Diagnostics.ProcessPriorityClass.Idle;

            //Greetings Screen
            Console.WriteLine("********************");
            Console.WriteLine("* Distributed MD5  *");
            Console.WriteLine("*      Cracker     *");
            Console.WriteLine("********************");
            Console.WriteLine("");
            Console.WriteLine("********************");
            Console.WriteLine("*      Client      *");
            Console.WriteLine("********************");
            Console.WriteLine("");
            Console.WriteLine("********************");
            Console.WriteLine("*     09000451     *");
            Console.WriteLine("********************");
            Console.WriteLine("");
            Console.WriteLine("--------------------");

            //connects to server
            Console.WriteLine("What is the IP of your server");
            String ServerName = Console.ReadLine();
            string hash       = serverConnect(ServerName);

            Console.WriteLine("Received Hash! " + hash);
            Thread.Sleep(50);

            //starts a thread listening for multicast terminate instructions, this allows the program to continue functioning while keeping a constant listen for global instructions.
            Thread terminatorThread = new Thread(new ThreadStart(terminateThread));

            terminatorThread.Start();

            //creates udp clients for listening!
            UdpClient udpClient  = new UdpClient();     //outgoing Udp
            UdpClient udpClient2 = new UdpClient(8010); //incoming port

            //section executes code while the thread is alive, this will include requesting new chunks to work through
            String resultYN = null;

            while (terminatorThread.IsAlive)
            {
                Byte[] sendBytes    = new Byte[1024]; // buffer to read the data into 1 kilobyte at a time
                Byte[] recieveBytes = new Byte[1024]; // buffer to read the data into 1 kilobyte at a time
                String textinput    = null;
                String returnData   = "";

                //sends an initial No to the server to request a chunk, as the server is keyed to pass out new chunks to clients that don't have an answer.
                try
                {
                    IPAddress remoteAddr = Dns.GetHostEntry(ServerName).AddressList[0]; //IP address of the server entered
                    udpClient.Connect(remoteAddr.ToString(), 8009);                     //address of the remotelocation
                    textinput = "n";
                    sendBytes = Encoding.ASCII.GetBytes(textinput.PadRight(1024));
                    udpClient.Send(sendBytes, sendBytes.GetLength(0));  //send the packet
                }//end of the try
                catch (Exception e)
                {
                    Console.WriteLine("Error with the Server Name: {0}", e.ToString());
                    Console.WriteLine("Did you start the Server First ?");
                }//end of the catch

                try
                {
                    //the IP Address.any allows any valid matching address for this machine to be used
                    //i.e. loopback, broadcast, IPv4, IPv6
                    IPEndPoint remoteIPEndPoint = new IPEndPoint(IPAddress.Any, 8009); //open port 8009 on this machine
                    udpClient2.Client.ReceiveTimeout = 500;                            //sets timeout to prevent the programming hanging if no reply is recieved
                    recieveBytes = udpClient2.Receive(ref remoteIPEndPoint);
                    returnData   = Encoding.ASCII.GetString(recieveBytes);
                }
                catch (Exception ex)
                {
                    Console.WriteLine("Packet Timed out");
                }

                //grabs the counter value from the returned chunk packet. it only needs one value as the clients know to increment by 100000 immediately
                int counter = 0;
                try
                {
                    counter = Convert.ToInt32(returnData);
                }
                catch
                {
                    counter = 0;
                    Console.ReadLine();
                    Environment.Exit(0);
                }

                Console.WriteLine("Recieved Chunk {0} - {1}", counter, counter + 100000); //included to provide visual indication that the program is recieving chunks
                String result = checkHash(hash, counter, counter + 100000);               //pass to the check hash function
                resultYN = result.Split()[0];                                             //the check hash function may pass back a yes result, this seperates the yes or no out for case checking

                //if the result is positive, the client sends a result packet straight away, that contains a yes terminate for the server, and the actual hash value
                if (resultYN == "y")
                {
                    try
                    {
                        IPAddress remoteAddr = Dns.GetHostEntry(ServerName).AddressList[0]; //IP address of the server entered
                        udpClient.Connect(remoteAddr.ToString(), 8009);                     //address of the remotelocation
                        //read in the text from the console
                        textinput = result;
                        sendBytes = Encoding.ASCII.GetBytes(textinput.PadRight(1024));
                        udpClient.Send(sendBytes, sendBytes.GetLength(0));  //send the packet
                    }//end of the try
                    catch (Exception e)
                    {
                        Console.WriteLine("Error with the Server Name: {0}", e.ToString());
                        Console.WriteLine("Did you start the Server First ?");
                    }//end of the catch
                }
            }

            //provides a delay to program close
            Console.WriteLine("");
            Console.ReadLine();
        }
Ejemplo n.º 29
0
	void Awake()
	{
		Debug.Assert(singleton == null);		// 複数作られないように
		singleton = this;
		Debug.Log(string.Format("peerId:{0:X08}", peerId));
		Debug.Assert(peerId != 0);

		send_fifo = new Queue<NetworkObjectData>();  // 送信用FIFO
		recv_fifo = new Queue<byte>();	 // 受信用FIFO

        send_udp = new UdpClient(); // 送信UDP
        send_udp.EnableBroadcast = true;
        send_udp.Connect(broadcast_addr,
						 LOCAL_TEST ? debug_send_port : PORT); // 接続
		var end_point = new IPEndPoint(IPAddress.Any, LOCAL_TEST ? debug_recv_port : PORT);
		recv_udp = new UdpClient(end_point); // 受信UDP
		recv_udp.EnableBroadcast = true;

        StartCoroutine(send_loop()); // 送信処理開始
        StartCoroutine(receive_loop()); // 受信処理開始

		object_dict_ = new Dictionary<ulong, GameObject>(); // リモートオブジェクト辞書
	}
Ejemplo n.º 30
0
        //provides initial connection to the server, and checks for timeout, if no response is found
        static string serverConnect(string ServerName)
        {
            //creates updclient on this machine to recieve data
            UdpClient udpClient  = new UdpClient();
            UdpClient udpClient2 = new UdpClient(8010);

            Byte[] sendBytes = new Byte[1024]; // buffer to read the data into 1 kilobyte at a time
            String textinput = null;

            //requests input of ip of server - consider switching to a multicast to join the server group

            String returnData = "";
            String hello      = null;
            String hash       = null;

            //sends data to the server address, in this case a Hello packet, if a hello is recieved back then the loop ends or until 4 packets have been sent
            int counter = 0;

            while (counter < 4)
            {
                try
                {
                    IPAddress remoteAddr = Dns.GetHostEntry(ServerName).AddressList[0]; //IP address of the server entered
                    udpClient.Connect(remoteAddr.ToString(), 8009);                     //address of the remotelocation
                    Console.WriteLine("Testing Connection");
                    //read in the text from the console
                    textinput = "Hello";
                    sendBytes = Encoding.ASCII.GetBytes(textinput.PadRight(1024));
                    udpClient.Send(sendBytes, sendBytes.GetLength(0));  //send the packet
                }//end of the try
                catch (Exception e)
                {
                    Console.WriteLine("Error with the Server Name: {0}", e.ToString());
                    Console.WriteLine("Did you start the Server First ?");
                }//end of the catch

                try
                {
                    Byte[] recieveBytes = new Byte[1024]; // buffer to read the data into 1 kilobyte at a time
                    //the IP Address.any allows any valid matching address for this machine to be used
                    //i.e. loopback, broadcast, IPv4, IPv6
                    IPEndPoint remoteIPEndPoint = new IPEndPoint(IPAddress.Any, 8010); //open port 8010 on this machine
                    udpClient2.Client.ReceiveTimeout = 500;                            //sets timeout to prevent the programming hanging if no reply is recieved
                    recieveBytes = udpClient2.Receive(ref remoteIPEndPoint);
                    returnData   = Encoding.ASCII.GetString(recieveBytes);
                    hello        = returnData.Split()[0];
                    hash         = returnData.Split()[1];
                }
                catch (Exception ex)
                {
                    Console.WriteLine("Packet {0} Timed out. Sending until 4!", counter + 1);
                    counter++;
                }

                if (counter == 4)
                {
                    Console.WriteLine("Unable to establish connection: program now terminating!");
                    Console.WriteLine("Press enter to close");
                }

                if (hello == "Hello")
                {
                    Console.WriteLine("Connected To Server!");
                    Console.WriteLine("");
                    counter = 4;
                }
            }
            udpClient.Close();
            udpClient2.Close();
            return(hash);
        }
Ejemplo n.º 31
0
        public async Task ConnectAsync()
        {
            AssertInitParams();
            if (IsConnected)
            {
                throw new InvalidOperationException($"{GetType().Name} уже подключен к устройству");
            }
            if (!IpEndPointParser.TryParse(_config.BedIpEndpoint, out _bedIpEndPoint))
            {
                throw new ArgumentException("Не верно указан адрес подключения к кровати. Требуемый формат - ip:port");
            }

            try
            {
                // очистим перед подключением все накопленные ошибки
                while (_lastExceptions.TryDequeue(out _))
                {
                }

                await InternalDisconectAsync().ConfigureAwait(false);

                _udpSendingClient = new UdpClient
                {
                    Client =
                    {
                        ReceiveTimeout = (int)_config.Timeout.TotalMilliseconds,
                        SendTimeout    = (int)_config.Timeout.TotalMilliseconds
                    }
                };

                _udpReceivingClient = new UdpClient(_bedIpEndPoint.Port)
                {
                    Client =
                    {
                        ReceiveTimeout = (int)_config.Timeout.TotalMilliseconds,
                        SendTimeout    = (int)_config.Timeout.TotalMilliseconds
                    }
                };
                _udpSendingClient.Connect(_bedIpEndPoint);
                _udpReceivingClient.Connect(_bedIpEndPoint);

                IsConnected = true;
                await UpdateRegistersValueAsync()
                .ConfigureAwait(false);

                _syncWorker = _workerController.StartWorker(_config.UpdateDataPeriod, async() =>
                {
                    if (_initialisingStatus == DeviceIsInitialising)
                    {
                        return;
                    }

                    try
                    {
                        //todo сюды бы токен отмены
                        await UpdateRegistersValueAsync()
                        .ConfigureAwait(false);
                    }
                    catch (Exception e)
                    {
                        IsConnected = false;
                        _workerController.CloseWorker(_syncWorker);
                        _lastExceptions.Enqueue(e);
                    }
                });
            }
            catch (DeviceConnectionException)
            {
                IsConnected = false;
                throw;
            }
            catch (SocketException e)
            {
                IsConnected = false;
                throw new DeviceConnectionException("Ошибка подключения к инверсионному столу", e);
            }
            catch (ObjectDisposedException e)
            {
                IsConnected = false;
                throw new DeviceConnectionException("Ошибка подключения к инверсионному столу", e);
            }
            catch (Exception e)
            {
                IsConnected = false;
                throw new DeviceProcessingException("Ошибка в ходе обработки данных от инверсионного стола", e);
            }
        }
Ejemplo n.º 32
0
        public NanoRdpTransport(string address, int tcpPort, int udpPort)
        {
            _address = address;
            _tcpPort = tcpPort;
            _udpPort = udpPort;

            _cancellationTokenSource = new CancellationTokenSource();
            IPAddress hostAddr = IPAddress.Parse(address);

            _controlProtoEp   = new IPEndPoint(hostAddr, _tcpPort);
            _streamingProtoEp = new IPEndPoint(hostAddr, _udpPort);

            _controlProtoClient   = new TcpClient(AddressFamily.InterNetwork);
            _streamingProtoClient = new UdpClient(AddressFamily.InterNetwork);

            _controlProtoClient.Client.Bind(new IPEndPoint(IPAddress.Any, 0));
            _streamingProtoClient.Client.Bind(new IPEndPoint(IPAddress.Any, 0));

            _controlProtoClient.Connect(_controlProtoEp);
            _streamingProtoClient.Connect(_streamingProtoEp);

            ChannelContext = new NanoChannelContext();

            void ProcessPacket(byte[] packetData)
            {
                try
                {
                    EndianReader reader = new EndianReader(packetData);
                    INanoPacket  packet = NanoPacketFactory.ParsePacket(packetData, ChannelContext);

                    if (packet.Header.PayloadType == NanoPayloadType.ChannelControl &&
                        packet as ChannelCreate != null)
                    {
                        ChannelContext.RegisterChannel((ChannelCreate)packet);
                    }
                    else if (packet.Header.PayloadType == NanoPayloadType.ChannelControl &&
                             packet as ChannelClose != null)
                    {
                        ChannelContext.UnregisterChannel((ChannelClose)packet);
                    }
                    else if (RemoteConnectionId == 0 && packet as ControlHandshake != null)
                    {
                        RemoteConnectionId = ((ControlHandshake)packet).ConnectionId;
                    }

                    bool success = _receiveQueue.TryAdd(packet);
                    if (!success)
                    {
                        logger.LogTrace($"Failed to add message to receive queue");
                    }
                }
                catch (NanoPackingException e)
                {
                    logger.LogError($"Failed to parse nano packet: {e.Message}", e);
                }
            }

            _controlProtoClient.ConsumeReceivedPrefixed(
                receiveResult => ProcessPacket(receiveResult),
                _cancellationTokenSource.Token
                );

            _streamingProtoClient.ConsumeReceived(
                receiveResult => ProcessPacket(receiveResult.Buffer),
                _cancellationTokenSource.Token
                );

            Task.Run(() =>
            {
                while (!_receiveQueue.IsCompleted)
                {
                    try
                    {
                        var message = _receiveQueue.Take();
                        MessageReceived?.Invoke(this, new MessageReceivedEventArgs <INanoPacket>(message));
                    }
                    catch (Exception e)
                    {
                        logger.LogError(
                            e, "Calling Nano MessageReceived failed!");
                    }
                }
            }, _cancellationTokenSource.Token);
        }
        private void DoWorkConnect(object sender, DoWorkEventArgs eventArgs)
        {
            try
            {

                IPEndPoint ipep = new IPEndPoint(IPAddress.Parse(Ip), Port);
                uclient = new UdpClient();
                uclient.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
                uclient.DontFragment = true;
                uclient.Connect(ipep);

                tcpclnt = new TcpClient();
                Console.WriteLine("Connecting.....");
                Status = 2;

                tcpclnt.NoDelay = true;

                tcpclnt.Connect(Ip, Port);
                Console.WriteLine("Connected");

                tcpclnt.GetStream().Write(publicKey, 0, publicKey.Length);
                byte[] serverPublicKey = new byte[72];
                tcpclnt.GetStream().Read(serverPublicKey, 0, 72);
                byte[] derivedKey =
                    exch.DeriveKeyMaterial(CngKey.Import(serverPublicKey, CngKeyBlobFormat.EccPublicBlob));

                StreamWriter stream = new StreamWriter(tcpclnt.GetStream());

                stream.WriteLine(Username);
                stream.Flush();

                Aes aes = new AesCryptoServiceProvider();
                aes.Key = derivedKey;
                byte[] bytes = new byte[aes.BlockSize / 8];
                bytes.Initialize();
                System.Buffer.BlockCopy(Username.ToCharArray(), 0, bytes, 0,
                    bytes.Length > Username.Length * sizeof(char) ? Username.Length * sizeof(char) : bytes.Length);
                aes.IV = bytes;
                ICryptoTransform encryptor = aes.CreateEncryptor(aes.Key, aes.IV);
                MemoryStream ms = new MemoryStream(64);
                CryptoStream csEncrypt = new CryptoStream(ms, encryptor, CryptoStreamMode.Write);
                byte[] passArr = Encoding.UTF8.GetBytes(Password);

                csEncrypt.Write(passArr, 0, passArr.Length);
                csEncrypt.Close();

                byte[] tosend = ms.ToArray();

                string encpass = Convert.ToBase64String(tosend, 0, tosend.Length);

                stream.WriteLine(encpass);
                stream.Flush();

                byte[] auth = new byte[sizeof(bool)];
                tcpclnt.GetStream().Read(auth, 0, sizeof(bool));

                bool result = BitConverter.ToBoolean(auth, 0);

                eventArgs.Result = result;

            }
            catch (Exception ioe)
            {
                eventArgs.Result = false;
            }

            if ((bool)eventArgs.Result)
            {
                Action act = new Action(() =>
                {
                    var netResource = new NetResource()
                    {
                        Scope = ResourceScope.GlobalNetwork,
                        ResourceType = ResourceType.Disk,
                        DisplayType = ResourceDisplaytype.Share,
                        RemoteName = "\\\\" + Ip + "\\C"
                    };

                    var result = WNetAddConnection2(
                        netResource,
                        Password,
                        null,
                        0x00000004 | 0x00000008 | 0x1000);

                    if (result != 0)
                    {
                        Console.WriteLine("Result not zero: " + result);
                    }
                });
                Thread t = new Thread(() => act());
                t.Start();

            }
        }
Ejemplo n.º 34
0
        static IPEndPoint serverEndpoint;   //Endpoint of the server

        static void Main(string[] args)
        {
            //Make sure we have the correct arguments being provided
            if (args.Length != 2)
            {
                Console.WriteLine("Usage: HammingTFTP.exe [error|noerror]  tftp-host file");
                Console.ReadLine();
                return;
            }

            try
            {
                //Determine if we are requesting with or without errors
                if (args[0] == "noerror")
                {
                    error = false;
                }

                //Grab the requested filename
                filename = args[1];

                //Get the ip address of the host
                var    host             = Dns.GetHostEntry("kayrun.cs.rit.edu");
                String serverAddressStr = "";
                foreach (var ip in host.AddressList)
                {
                    if (ip.AddressFamily == AddressFamily.InterNetwork && ip.ToString().Substring(0, 3) == "129")
                    {
                        serverAddressStr = ip.ToString();
                    }
                }
                IPAddress serverAddress;
                IPAddress.TryParse(serverAddressStr, out serverAddress);

                //Connect to the server endpoint
                serverEndpoint = new IPEndPoint(serverAddress, 7000);
                client         = new UdpClient();
                client.Connect(serverEndpoint);

                //Write the initial request block
                byte[] octToByte   = Encoding.ASCII.GetBytes("octet");
                byte[] fileToBytes = Encoding.ASCII.GetBytes(filename);
                byte[] request     = new byte[4 + octToByte.Length + fileToBytes.Length];

                request[0] = 0;
                request[1] = (byte)(error ? 2 : 1);
                Array.Copy(fileToBytes, 0, request, 2, fileToBytes.Length);
                request[fileToBytes.Length + 2] = 0;
                Array.Copy(octToByte, 0, request, fileToBytes.Length + 3, octToByte.Length);
                request[request.Length - 1] = 0;

                //Send the block
                client.Send(request, request.Length);

                byte[] response = client.Receive(ref serverEndpoint);

                //If we receive an error, print the message and return
                if (response[1] == 5)
                {
                    Console.WriteLine(Encoding.ASCII.GetString(response.Skip(4).ToArray()));
                    return;
                }

                //Remove the opcode and block number
                response = response.Skip(4).ToArray();

                //Download the rest of the file
                DownloadFile(response);
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                Console.ReadLine();
            }
        }
Ejemplo n.º 35
0
    void SceneEnterSuccess(string jsonData)
    {
        Debug.Log ("SceneEnterSuccess");
        Debug.Log ("SceneEnterSuccess: "+jsonData);
        executeInUpdate.Enqueue (SceneEnterSuccessSync);

        var N = JSON.Parse (jsonData);
        myID = (byte)N ["characterID"].AsInt;

        //Debug.Log (N["enemies"]);
        enemies.Clear ();
        foreach(string key in N["enemies"].AsObject.Keys) {
            JSONNode enemy = N["enemies"][key];
            Debug.Log ("Found enemy "+key+":"+enemy.ToString());
            byte characterID = (byte) int.Parse(key);
            executeInUpdate.Enqueue(delegate() {
                //if(characterID != myID) enemies.Add(characterID, Instantiate(enemyPrefab, Vector3.zero, Quaternion.identity) as GameObject);
                if(characterID != myID) {
                    //enemies.Add(characterID, Instantiate(enemyPrefab, Vector3.zero, Quaternion.identity) as GameObject);
                    UMADynamicAvatar avatar = LoadUMA(enemy["umaPackedRecipe"], null, "Enemy", false);
                    enemies.Add (characterID, MakeEnemy(avatar));
                }
            });

        }

        if (udpClient != null) {
            udpClient.Close();
        }
        udpClient = new UdpClient (1100);
        udpClient.Connect(alternativMUDClientScript.hostname, N["port"].AsInt);
    }
Ejemplo n.º 36
0
 public Server()
 {
     //IP adress that will recieve the audio bytes (RECIPIENT - RECIP)
     sender.Connect("192.168.1.117", 11000);
 }
Ejemplo n.º 37
0
        public static void Connect()
        {
            form.Log("connecting...", Color.DarkGray);
            string serverIP   = form.textBoxServerIP.Text;
            int    serverPort = (int)form.numericUpDownPort.Value;

            try {
                tcpToServer = new TcpClient()
                {
                    NoDelay = true
                };
                tcpToServer.Connect(serverIP, serverPort);

                udpToServer = new UdpClient(tcpToServer.Client.LocalEndPoint as IPEndPoint);
                udpToServer.Connect(serverIP, serverPort);
            }
            catch (SocketException) {//connection refused
                Close();
                form.Log("failed\n", Color.Red);
                form.EnableButtons();
                return;
            }
            form.Log("connected\n", Color.Green);

            Stream stream = tcpToServer.GetStream();

            swriter = new BinaryWriter(stream);
            sreader = new BinaryReader(stream);

            form.Log("checking version...", Color.DarkGray);
            swriter.Write(Database.bridgeVersion);
            if (!sreader.ReadBoolean())
            {
                form.Log("mismatch\n", Color.Red);
                form.buttonDisconnect.Invoke(new Action(form.buttonDisconnect.PerformClick));
                return;
            }
            form.Log("match\n", Color.Green);
            form.Log("logging in...", Color.DarkGray);
            swriter.Write(form.textBoxUsername.Text);
            swriter.Write(form.textBoxPassword.Text);
            swriter.Write(NetworkInterface.GetAllNetworkInterfaces().Where(nic => nic.OperationalStatus == OperationalStatus.Up).Select(nic => nic.GetPhysicalAddress().ToString()).FirstOrDefault());
            switch ((AuthResponse)sreader.ReadByte())
            {
            case AuthResponse.success:
                if (sreader.ReadBoolean())                 //if banned
                {
                    MessageBox.Show(sreader.ReadString()); //ban message
                    form.Log("you are banned\n", Color.Red);
                    goto default;
                }
                break;

            case AuthResponse.unknownUser:
                form.Log("unknown username\n", Color.Red);
                goto default;

            case AuthResponse.wrongPassword:
                form.Log("wrong password\n", Color.Red);
                goto default;

            default:
                form.buttonDisconnect.Invoke(new Action(form.buttonDisconnect.PerformClick));
                return;
            }
            form.Log("success\n", Color.Green);
            connected = true;

            swriter.Write((byte)0);//request query
            new Thread(new ThreadStart(ListenFromServerTCP)).Start();
            new Thread(new ThreadStart(ListenFromServerUDP)).Start();
            ListenFromClientTCP();
        }
Ejemplo n.º 38
0
        private async Task <bool> IsUdpServerUp(string address, int port)
        {
            UdpClient udpClient = new UdpClient();

            try
            {
                // udpClient.Client.ReceiveTimeout not used in Async calls
                udpClient.Connect(address, port);
                IPEndPoint RemoteIpEndPoint = new IPEndPoint(IPAddress.Any, 0);
                byte[]     sendBytes        = Packet.MakeLoginPacket();
                udpClient.Send(sendBytes, sendBytes.Length);
                var receiveTask = udpClient.ReceiveAsync();
                var tsk         = await Task.WhenAny(receiveTask, Task.Delay(TimeSpan.FromSeconds(TIMEOUTSEC)));

                if (tsk == receiveTask)
                {
                    var result = await receiveTask;
                    var header = ByteArrayToNewStuff(result.Buffer);
                    if (((uint)header.Flags & 0x800000u) != 0 && result.Buffer.Length >= 24)
                    {
                        byte[] newBytes = new byte[4];
                        Buffer.BlockCopy(result.Buffer, 20, newBytes, 0, 4);
                        var n     = BitConverter.ToUInt32(newBytes, 0);
                        var debug = string.Format("Got {0}: ", n);
                        for (int i = 0; i < result.Buffer.Length; ++i)
                        {
                            var bytn = result.Buffer[i];
                            debug += bytn.ToString("X2");
                            if (i == 4 || i == 8 || i == 12 || i == 14 || i == 16 || i == 18 || i == 20)
                            {
                                debug += " ";
                            }
                        }
                        System.Diagnostics.Debug.WriteLine(debug);
                    }
                    // TODO - extract number of players from buffer
                    return(true);
                }
                else
                {
                    // TODO: clean up udpClient?
                    return(false);
                }
            }
            catch (SocketException e)
            {
                if (e.ErrorCode == 10054)
                {
                    return(false);
                }
                else
                {
                    return(false);
                }
            }
            finally
            {
                if (udpClient != null)
                {
                    udpClient.Close();
                    udpClient = null;
                }
            }
        }
Ejemplo n.º 39
0
 public Client(int localPort, string destIP, int destPort)
 {
     client = new UdpClient(localPort);
     client.Connect(destIP, destPort);
     packet = new Packet();
 }
Ejemplo n.º 40
0
 void Start()
 {
     client = new UdpClient();
     client.Connect(host, port);
 }
    public void ReceiveResponse()
    {
        try
        {
            var buffer = new byte[8192];
            int received = 0;

            try
            {
                received = sck.Receive(buffer, SocketFlags.None);
            }
            catch (Exception) { }

            if (received == 0) return;

            var data = new byte[received];
            Array.Copy(buffer, data, received);

            Packet pack;
            bool result = Packet.DeserializePacket(data, out pack);

            if (pack.Type == PacketType.Message)
            {
                string dataString = Encryption.DecryptI(pack.Content.ToString());

                if (dataString.StartsWith("VALIDATED "))
                {
                    if (dataString.Replace("VALIDATED ", "").StartsWith("VALID"))
                    {
                        validClient = true;
                        Debug.Log("[" + DateTime.Now.ToString("HH:mm:ss") + "] [INFO] : Validation returns positive.");

                        ID = dataString.Replace("VALIDATED VALID ", "");

                        byte[] contents = Packet.SerializePacket(new Packet(Encryption.EncryptI("CONNECT"), PacketType.UDPConnect));
                        sck.Send(contents);

                        Debug.Log("[" + DateTime.Now.ToString("HH:mm:ss") + "] [INFO] : Requesting UDP connection stream...");
                    }
                    else if (dataString.Replace("VALIDATED ", "") == "INVALID")
                    {
                        Debug.Log("[" + DateTime.Now.ToString("HH:mm:ss") + "] [FATAL] : Security key is invalid! Disconnecting...");
                        sck.Close();
                    }
                }
                else if (dataString == "/servershutdown")
                {
                    Debug.Log("[" + DateTime.Now.ToString("HH:mm:ss") + "] [WARN] : You are being dropped by the server!");
                    sck.Close();
                }
                else
                    Debug.Log("[" + DateTime.Now.ToString("HH:mm:ss") + "] [SERVER] : " + dataString);
            }
            else if (pack.Type == PacketType.UDPConnect)
            {
                if (Encryption.DecryptI(pack.Content.ToString()).StartsWith("WAITING "))
                {
                    Debug.Log("[" + DateTime.Now.ToString("HH:mm:ss") + "] [INFO] : Attempting to connect to UDP server...");

                    string port = Encryption.DecryptI(pack.Content.ToString());
                    port = port.Replace("WAITING ", "");

                    //Try connect to server
                    udpPort = int.Parse(port);

                    UDPFirstContact = true;

                    client = new UdpClient();
                    ep = new IPEndPoint(ipAd, udpPort); // endpoint where server is listening
                    client.Connect(ep);

                    StartCoroutine(UDPPing());

                    StartCoroutine(UDPConnect());
                }
            }
        }
        catch (Exception ex)
        {
            Packet packet = new Packet(Encryption.EncryptI("ERROR-REPORT -- [" + DateTime.Now.ToString("HH:mm:ss") + "] [FATAL] : Oops something went wrong :S \n" + ex), PacketType.ErrorReport);
            Debug.Log("[" + DateTime.Now.ToString("HH:mm:ss") + "] [FATAL] : Oops something went wrong :S \n" + ex);

            byte[] bytes = Packet.SerializePacket(packet);

            sck.Send(bytes);
            sck.Close();
        }
    }
Ejemplo n.º 42
0
    private UdpClient getClient()
    {
        if (udp_client == null) {
            udp_client = new UdpClient();
            udp_client.Connect(System.Net.IPAddress.Parse("127.0.0.1"), 9451);
        }

        return udp_client;
    }
Ejemplo n.º 43
0
        /// <summary>
        /// Create a new CDKey Server Client Emulator Instance
        /// </summary>
        /// <param name="CDKeyServerIPEndPoint">CDKey Server IP Endpoint to Connect to</param>
        /// <param name="RoundTips">Ammount of Retrys to Send to the CD Key Server before finishing</param>
        /// <param name="InterPacketGap">Milliseconds to wait between the Retrys</param>
        public CDKeyServerClientEmulator(IPEndPoint CDKeyServerIPEndPoint, int RoundTrips, int InterPacketGap)
        {
            this.cdKeyServer = CDKeyServerIPEndPoint;

            this.state = CDKeyServerClientEmulatorState.Initializing;
            //Add InstanceToInstanceNumber
            cdKeyServerInstanceCount++;
            this.instanceId = cdKeyServerInstanceCount;

            this.currentCDKeyServerRoundTripCounter        = 0;
            this.currentCDKeyServerRoundTripSuccessCounter = 0;

            this.roundTripWatcher = new Stopwatch();

            //Start Initalizing the Client
            if (this.initalizeUDPClient())
            {
                ///Lets Hammer him
                for (currentCDKeyServerRoundTripCounter = 0; currentCDKeyServerRoundTripCounter < RoundTrips; currentCDKeyServerRoundTripCounter++)
                {
                    this.state = CDKeyServerClientEmulatorState.Connecting;
                    client.Connect(cdKeyServer);

                    roundTripWatcher.Start();
                    if (client.Client.Connected)
                    {
                        //Client is Connected
                        this.state = CDKeyServerClientEmulatorState.Connected;

                        if (sendBuffer != null)
                        {
                            Array.Clear(sendBuffer, 0, sendBuffer.Length);
                        }
                        if (recieveBuffer != null)
                        {
                            Array.Clear(recieveBuffer, 0, recieveBuffer.Length);
                        }

                        sendBuffer = Encoding.UTF8.GetBytes(
                            /* Decode it with Xor */
                            Xor(
                                /* Generate Fake Request */
                                GenerateRandomClientCDKeyValidationRequest()
                                )
                            );

                        //Send Data to the Client
                        client.Send(sendBuffer, sendBuffer.Length);

                        //Now lets Wait for the Request Recieve the Client Server Token
                        this.recieveBuffer = client.Receive(ref CDKeyServerIPEndPoint);

                        //Check if we got some Data
                        if (recieveBuffer.Length != 0)
                        {
                            //We recived Something

                            //Decode it with Xor
                            String Response = Xor(Encoding.UTF8.GetString(this.recieveBuffer));

                            //Lets check if we got an Valid Response
                            if (recieveDataPattern.Match(Response).Success)
                            {
                                this.currentCDKeyServerRoundTripSuccessCounter++;
                            }
                        }
                    }
                    else
                    {
                        this.throwCritical("Unable to connect to CDKey Server IP:" + cdKeyServer.Address.ToString() + ":" + cdKeyServer.Port.ToString());
                    }

                    roundTripWatcher.Stop();

                    if (averageRoundtripTime == 0)
                    {
                        averageRoundtripTime = roundTripWatcher.Elapsed.Milliseconds;
                    }
                    else
                    {
                        averageRoundtripTime = roundTripWatcher.Elapsed.Milliseconds + averageRoundtripTime / 2;
                    }
                    //Add up the Retry Counter
                    this.currentCDKeyServerRoundTripCounter++;
                    Console.WriteLine(averageRoundtripTime + ":" + currentCDKeyServerRoundTripSuccessCounter + ":" + currentCDKeyServerRoundTripCounter);
                }
            }
        }
Ejemplo n.º 44
0
 public void Connect()
 {
     _client.Connect(_host);
     IsConnected = true;
 }
Ejemplo n.º 45
0
    public void zbiornik_funkcja()
    {

        var client = new UdpClient();
        IPEndPoint ep = new IPEndPoint(IPAddress.Parse("192.168.42.42"), 8888);
        client.Connect(ep);
        // send data
        Byte[] sendBytes = System.Text.Encoding.ASCII.GetBytes("A");
        client.Send(sendBytes, sendBytes.Length);
        //receive data
        var receivedData = client.Receive(ref ep);
        string returnData = System.Text.Encoding.ASCII.GetString(receivedData);
        stan_zbiornika.Text = returnData + "%";

        if (Convert.ToInt16(returnData) > 0)
        {
            if (Convert.ToInt16(returnData) > 25)
            {
                if (Convert.ToInt16(returnData) > 50)
                {
                    if (Convert.ToInt16(returnData) > 75)
                    {
                        if (Convert.ToInt16(returnData) > 90)
                        {
                            Image1.ImageUrl = "~/pic/100.png";
                        }
                        else Image1.ImageUrl = "~/pic/75.png";
                    }
                    else Image1.ImageUrl = "~/pic/50.png";
                }
                else Image1.ImageUrl = "~/pic/25.png";
            }
            else
            {
                Image1.ImageUrl = "~/pic/10.png";
                label02.Text = " NISKI POZIOM WODY";
                label02.Visible = true;
            }


        }

        var client2 = new UdpClient();
        IPEndPoint ep2 = new IPEndPoint(IPAddress.Parse("192.168.42.42"), 8888);
        client2.Connect(ep2);

        // send data
        Byte[] sendBytes2 = System.Text.Encoding.ASCII.GetBytes("B");
        client2.Send(sendBytes2, sendBytes2.Length);
        // then receive data
        var receivedData2 = client2.Receive(ref ep2);
        string returnData2 = System.Text.Encoding.ASCII.GetString(receivedData2);


        if (returnData2 == "ON")
        {
            stan_pompy.Text = "ON";
            Image2.ImageUrl = "~/pic/pompa_on.png";
        }
        else if (returnData2 == "OFF")
        {
            stan_pompy.Text = "OFF";
            Image2.ImageUrl = "~/pic/pompa_off.png";
        }
    }
Ejemplo n.º 46
0
    static void Main(string[] args)
    {
        string serverIp;
        int httpPort;
        int serverPort;
        const string STOP = "stop";

        Console.WriteLine("Enter server IP address:");

        serverIp = Console.ReadLine();

        Console.WriteLine("Enter HTTP port number:");

        httpPort = int.Parse(Console.ReadLine());

        Console.WriteLine("Connection to {0}:{1}", serverIp, httpPort);

        var request = (HttpWebRequest)WebRequest.Create("http://" + serverIp + ":" + httpPort + "/auth");
        var postData = "thing1=hello";
        postData += "&thing2=world";
        var data = Encoding.ASCII.GetBytes(postData);
        request.Method = "POST";
        request.ContentType = "application/x-www-form-urlencoded";
        request.ContentLength = data.Length;
        var stream = request.GetRequestStream();
        stream.Write(data, 0, data.Length);
        var response = (HttpWebResponse)request.GetResponse();
        var authRes = new StreamReader(response.GetResponseStream()).ReadToEnd();

        Console.WriteLine("Auth response:{0}", authRes);

        JSONNode auth = JSON.Parse(authRes);

        Console.WriteLine("Session ID is {0}", auth["sessionId"]);
        Console.WriteLine(
            "Cipher Key, Nonce, and MacKey:{0}, {1}, {2}",
            auth["cipherData"]["base64"]["cipherKey"],
            auth["cipherData"]["base64"]["cipherNonce"],
            auth["cipherData"]["base64"]["macKey"]
        );

        Console.WriteLine("Enter UDP server port number:");

        serverPort = int.Parse(Console.ReadLine());

        Console.WriteLine("Connection to {0}:{1}", serverIp, serverPort);

        int myPort = 54061;

        // connect to UDP server and send message
        UdpClient client = new UdpClient(myPort);
        IPEndPoint endPoint = new IPEndPoint(IPAddress.Parse(serverIp), serverPort);
        client.Connect(endPoint);

        Console.WriteLine("Prepare encryption");

        // prepare encryption
        Guid sid = new Guid(auth["sessionId"]);
        byte[] cipherKey = System.Convert.FromBase64String(auth["cipherData"]["base64"]["cipherKey"]);
        byte[] cipherNonce = System.Convert.FromBase64String(auth["cipherData"]["base64"]["cipherNonce"]);
        byte[] macKey = System.Convert.FromBase64String(auth["cipherData"]["base64"]["macKey"]);
        var crypto = new Crypto(sid, cipherKey, cipherNonce, macKey);

        byte[] packet = Encoding.ASCII.GetBytes("{\"command\":1,\"payload\":\"Hello\"}");
        var epacket = crypto.Encrypt(packet);

        client.Send(epacket, epacket.Length);

        Console.WriteLine("UDP message sent: size is {0}", epacket.Length);

        Console.WriteLine("Waiting for server message...");

        byte[] recData = client.Receive(ref endPoint);

        Console.WriteLine("Try decrypting...");

        var dpack = crypto.Decrypt(recData);

        Console.WriteLine("message from server: {0}", Encoding.UTF8.GetString(dpack));
    }
Ejemplo n.º 47
0
    /// <summary>
    /// Method that will start broadcasting packets to find a smart device
    /// </summary>
    private void StartSendingIP()
    {
        sender = new UdpClient (NaviConnectionSDK.UDP_SERVER_PORT, AddressFamily.InterNetwork);
        IPEndPoint groupEP;
        #if UNITY_ANDROID && !UNITY_EDITOR
        string hsIP = GetMobileHotspotObj().Call<string>("getBroadcastAddress");
        if (hsIP != null) {
        groupEP = new IPEndPoint (IPAddress.Parse( hsIP ), NaviConnectionSDK.REMOTE_PORT);
        } else {
        groupEP = new IPEndPoint (IPAddress.Broadcast, NaviConnectionSDK.REMOTE_PORT);
        }
        #else
        groupEP = new IPEndPoint (IPAddress.Broadcast, NaviConnectionSDK.REMOTE_PORT);
        #endif
        sender.Connect (groupEP);

        InvokeRepeating(SEND_DATA_METHOD_STR,0,0.3f); //send data every half a second
    }
Ejemplo n.º 48
0
    /// <summary>
    /// Method that will start broadcasting packets to find a smart device
    /// </summary>
    private void StartSendingIP()
    {
        sender = new UdpClient (NaviConnectionSDK.UDP_SERVER_PORT, AddressFamily.InterNetwork);
        IPEndPoint groupEP = new IPEndPoint (IPAddress.Broadcast, NaviConnectionSDK.REMOTE_PORT);
        sender.Connect (groupEP);

        InvokeRepeating(SEND_DATA_METHOD_STR,0,0.5f); //send data every half a second
    }
Ejemplo n.º 49
0
        /// <summary>
        /// Sends an <see cref="ISnmpMessage"/> and handles the response from agent.
        /// </summary>
        /// <param name="request">The <see cref="ISnmpMessage"/>.</param>
        /// <param name="receiver">Agent.</param>
        /// <param name="udpSocket">The UDP <see cref="Socket"/> to use to send/receive.</param>
        /// <param name="registry">The user registry.</param>
        /// <returns></returns>
        public static async Task <ISnmpMessage> GetResponseAsync(this ISnmpMessage request, int timeout, IPEndPoint receiver, UserRegistry registry, UdpClient udpSocket, CancellationToken cancellationToken = default)
        {
            if (request == null)
            {
                throw new ArgumentNullException(nameof(request));
            }

            if (udpSocket == null)
            {
                throw new ArgumentNullException(nameof(udpSocket));
            }

            if (registry == null)
            {
                throw new ArgumentNullException(nameof(registry));
            }

            var requestCode = request.TypeCode();

            if (requestCode == SnmpType.TrapV1Pdu || requestCode == SnmpType.TrapV2Pdu || requestCode == SnmpType.ReportPdu)
            {
                throw new InvalidOperationException(string.Format(CultureInfo.InvariantCulture, "not a request message: {0}", requestCode));
            }

            var bytes = request.ToBytes();
            UdpReceiveResult result;

            udpSocket.Connect(receiver);
            var recvTask = udpSocket.ReceiveAsync();

            if (timeout > 0)
            {
                var timeoutTask = Task.Delay(timeout, cancellationToken);
                await udpSocket.SendAsync(bytes, bytes.Length).ConfigureAwait(false);

                var r = await Task.WhenAny(new Task[] { recvTask, timeoutTask }).ConfigureAwait(false);

                cancellationToken.ThrowIfCancellationRequested();
                if (r == timeoutTask)
                {
                    udpSocket.Close();
                    throw TimeoutException.Create(receiver.Address, timeout);
                }
            }
            result = await recvTask.ConfigureAwait(false);

            // Passing 'count' is not necessary because ParseMessages should ignore it, but it offer extra safety (and would avoid an issue if parsing >1 response).
            var response     = MessageFactory.ParseMessages(result.Buffer, 0, result.Buffer.Length, registry)[0];
            var responseCode = response.TypeCode();

            if (responseCode == SnmpType.ResponsePdu || responseCode == SnmpType.ReportPdu)
            {
                var requestId  = request.MessageId();
                var responseId = response.MessageId();
                if (responseId != requestId)
                {
                    throw OperationException.Create(string.Format(CultureInfo.InvariantCulture, "wrong response sequence: expected {0}, received {1}", requestId, responseId), receiver.Address);
                }

                return(response);
            }

            throw OperationException.Create(string.Format(CultureInfo.InvariantCulture, "wrong response type: {0}", responseCode), receiver.Address);
        }
Ejemplo n.º 50
0
        static string serverStart(string hash)
        {
            string    returnData = "";
            UdpClient udpClient  = new UdpClient();                            //udp client for sending data
            UdpClient udpClient2 = new UdpClient(8009);                        //udp client fixed on port 8009 for receiving data

            Byte[]     recieveBytes     = new Byte[1024];                      // buffer to read the data into 1 kilobyte at a time
            Byte[]     sendBytes        = new Byte[1024];                      // buffer to read the data into 1 kilobyte at a time
            IPEndPoint remoteIPEndPoint = new IPEndPoint(IPAddress.Any, 8009); //open port 8009 on this machine
            String     reply            = null;
            String     splitYN          = null;
            String     hashValue        = null;
            int        count            = 0;
            DateTime   startTime        = DateTime.Now;


            //Path to Logfile
            String       fileName = "f:\\09000451-log.txt";
            StreamWriter Swriter;      //stream to write to a logfile
            StreamReader Sreader;      //stream to read from logfile

            if (File.Exists(fileName)) //check to see if the file exists
            {
                Console.WriteLine("Log File found! Continuing from last entry!");
                String inputtext = null;
                Sreader = new StreamReader(fileName);
                while (Sreader.Peek() >= 0)
                {
                    inputtext = Sreader.ReadLine();
                }
                String tempcount = inputtext.Split()[1];
                try
                {
                    //checks to see if there is at least one numerical entry in the logfile, if not, count will start at 0, but this does stop the program crashing if there is no logfile contents
                    count = Convert.ToInt32(tempcount);
                    Console.WriteLine("Starting from {0}", count);
                }
                catch (FormatException e)
                {
                    Console.WriteLine("Unable to find any entries in logfile! Starting from 0!");
                    count = 0;
                }
                Sreader.Close();
            }
            else
            {
                //file does not already exist start from the begining
                Console.WriteLine("No Log File found! Creating now!");
                Swriter   = new StreamWriter(fileName, false); //name of file
                startTime = DateTime.Now;
                Swriter.WriteLine("Hash {0} started on {1}", hash, startTime);
                Swriter.Close();
            }//end of the IF else
            Swriter = new StreamWriter(fileName, true); //name of file
            Console.WriteLine("Server is Started");
            Console.WriteLine("");
            Console.WriteLine("Clients can now connect");

            //keep recieving packets until a terminate is sent from a client, in this case terminate is in the form of a yes packet sent by a machine discovering the correct hash
            while (splitYN != "y")
            {
                recieveBytes = udpClient2.Receive(ref remoteIPEndPoint);
                returnData   = Encoding.ASCII.GetString(recieveBytes);
                splitYN      = returnData.Split()[0];
                hashValue    = returnData.Split()[1];
                if (splitYN == "Hello")
                {
                    //if a hello packet is detected, sends a confirm hello back with the hash attached to the datagram, so the clients recieve hashes straight away
                    Console.WriteLine(remoteIPEndPoint.Address.ToString() + " connected!");
                    IPAddress remoteAddr = remoteIPEndPoint.Address; //IP address of the server entered
                    udpClient.Connect(remoteAddr.ToString(), 8010);  //address of the remotelocation
                    reply     = "Hello " + hash;
                    sendBytes = Encoding.ASCII.GetBytes(reply.PadRight(1024));
                    udpClient.Send(sendBytes, sendBytes.GetLength(0));  //send the packet
                }
                else if (splitYN == "n")
                {
                    //writes to the logfile to let it know what chunks have been sent
                    Console.WriteLine("Sending chunk to " + remoteIPEndPoint.Address.ToString());
                    String ip = remoteIPEndPoint.Address.ToString();
                    Swriter.WriteLine("Sent {0} - {1} to {2}", count, count + 100000, ip);
                    Swriter.Flush();                                 // included to ensure data is written to the logfile immediately
                    IPAddress remoteAddr = remoteIPEndPoint.Address; //IP address of the server entered
                    udpClient.Connect(remoteAddr.ToString(), 8010);  //address of the remotelocation
                    reply     = count.ToString();
                    sendBytes = Encoding.ASCII.GetBytes(reply.PadRight(1024));
                    udpClient.Send(sendBytes, sendBytes.GetLength(0)); //send the packet
                    count = count + 100000;                            //increments the count ready to send the next chunk on
                }
                else if (splitYN == "y")
                {
                    //once a tes packet is received these statements kick in, writing to both screen and file
                    DateTime endTime = DateTime.Now;
                    Console.WriteLine("HASH FOUND!");
                    Console.WriteLine("{0} converts to {1}", hash, hashValue);
                    Swriter.WriteLine("");
                    Swriter.WriteLine("Cleartext Found: the hash converst to {0}!", hashValue);
                    Swriter.WriteLine("");
                    Swriter.WriteLine("Cracking ended at {0}", endTime);
                    Swriter.Close();
                }
            }

            //the actual value of the hash will not be returned until the while loop closes on receipt of a yes packet
            return(hashValue);
        }
    // Use this for initialization
    void Start()
    {
        remoteEndPoint = new IPEndPoint(IPAddress.Parse(ip), port);

        client = new UdpClient();
        client.Connect(remoteEndPoint);
    }
Ejemplo n.º 52
0
        public static async Task PingUdpPort(Tag tag, Byte[] sendBytes)
        {
            try
            {
                UdpClient udpClient = new UdpClient(tag.Port);
                Socket    uSocket   = udpClient.Client;
                uSocket.ReceiveTimeout = 5000;
                udpClient.Connect(tag.Ip_Address, tag.Port);
                udpClient.Send(sendBytes, sendBytes.Length);
                IPEndPoint RemoteIpEndPoint = tag.RemoteIpEndPoint;
                Byte[]     receiveBytes     = udpClient.Receive(ref RemoteIpEndPoint);
                tag.is_open         = true;
                tag.PortDescription = tag.Ip_Address + ":" + tag.Port + " is open";
                udpClient.Close();
            }
            catch (SocketException ex)
            {
                tag.is_open = false;

                switch (ex.ErrorCode)
                {
                case 10054:
                    WorkerLogger.TraceLog(MessageType.Debug, tag.PortDescription);
                    tag.PortDescription = tag.Ip_Address + ":" + tag.Port + ":: " + "is closed or connection blocked by firewall";
                    break;

                case 10048:
                    tag.PortDescription = "Port " + tag.Port + ":: " + "Address already in use";
                    WorkerLogger.TraceLog(MessageType.Debug, tag.PortDescription);
                    break;

                case 10051:
                    tag.PortDescription = "Port " + tag.Port + "::" + "Network is unreachable";
                    WorkerLogger.TraceLog(MessageType.Debug, tag.PortDescription);
                    break;

                case 10050:
                    tag.PortDescription = tag.Ip_Address + ":" + tag.Port + "::" + "Network is down";
                    WorkerLogger.TraceLog(MessageType.Debug, tag.PortDescription);
                    break;

                case 10056:
                    tag.PortDescription = tag.Ip_Address + ":" + tag.Port + "::" + "Socket is already connected";
                    WorkerLogger.TraceLog(MessageType.Debug, tag.PortDescription);
                    break;

                case 10060:
                    tag.PortDescription = tag.Ip_Address + ":" + tag.Port + "::" + "Connection timed out, the connection is maybe blocked by the firewall";
                    WorkerLogger.TraceLog(MessageType.Debug, tag.PortDescription);
                    break;

                case 10061:
                    tag.PortDescription = tag.Ip_Address + ":" + tag.Port + ":" + "Connection refused::No server application is running";
                    WorkerLogger.TraceLog(MessageType.Debug, tag.PortDescription);
                    break;

                case 10064:
                    tag.PortDescription = tag.Ip_Address + ":" + tag.Port + "::" + "Host is down";
                    WorkerLogger.TraceLog(MessageType.Debug, tag.PortDescription);
                    break;

                default:
                    tag.PortDescription = tag.Ip_Address + ":" + tag.Port + "::" + "CodeError: " + ex.ErrorCode + ":: " + ex.Message;
                    WorkerLogger.TraceLog(MessageType.Debug, tag.PortDescription);
                    break;
                }
            }
        }
Ejemplo n.º 53
0
    void Start()
    {
        Debug.Log("test");

        int port = 4023;
        UdpClient udpClient = new UdpClient(port);
        try
        {
            udpClient.Connect("142.232.18.112", port);

            // Sends a message to the host to which you have connected.
            Byte[] sendBytes = Encoding.ASCII.GetBytes("Is anybody there?");

            udpClient.Send(sendBytes, sendBytes.Length);

            // Sends a message to a different host using optional hostname and port parameters.
            UdpClient udpClientB = new UdpClient();
            udpClientB.Send(sendBytes, sendBytes.Length, "AlternateHostMachineName", port);

            //IPEndPoint object will allow us to read datagrams sent from any source.
            IPEndPoint RemoteIpEndPoint = new IPEndPoint(IPAddress.Any, 0);

            // Blocks until a message returns on this socket from a remote host.
            Byte[] receiveBytes = udpClient.Receive(ref RemoteIpEndPoint);
            string returnData = Encoding.ASCII.GetString(receiveBytes);

            // Uses the IPEndPoint object to determine which of these two hosts responded.
            Console.WriteLine("This is the message you received " +
                                         returnData.ToString());
            Console.WriteLine("This message was sent from " +
                                        RemoteIpEndPoint.Address.ToString() +
                                        " on their port number " +
                                        RemoteIpEndPoint.Port.ToString());

            udpClient.Close();
            udpClientB.Close();

        }
        catch (Exception e)
        {
            Console.WriteLine(e.ToString());
        }

        /*
        int myReliableChannelId; // above Start()
        myReliableChannelId = config.AddChannel(QosType.Reliable);
        int maxConnections = 10;
        HostTopology topology = new HostTopology(config, maxConnections);

        int socketId; // above Start()
        int socketPort = 8888; // Also a class member variable
        socketId = NetworkTransport.AddHost(topology, socketPort);
        Debug.Log("Socket Open. SocketId is: " + socketId);

        int myReliableChannelId; // above Start()
        myReliableChannelId = config.AddChannel(QosType.Reliable);
        int maxConnections = 10;
        HostTopology topology = new HostTopology(config, maxConnections);

        int socketId;
        int socketPort = 4023;
        byte error;
        socketId = NetworkTransport.AddHost(topology, socketPort);
        var connectionId = NetworkTransport.Connect(socketId, "127.0.0.1", socketPort, 0, out error);

        byte[] buffer = new byte[1024];
        Stream stream = new MemoryStream(buffer);
        BinaryFormatter formatter = new BinaryFormatter();
        formatter.Serialize(stream, "HelloServer");

        int bufferSize = 1024;
        NetworkTransport.Send(socketId, connectionId, myReliableChannelId, buffer, bufferSize, out error);
         */
    }
Ejemplo n.º 54
0
 public void UdpSendSettings(string Host, int Port) // Connect Socket for Specific IP and Port
 {
     UDP_Client.Connect(Host, Port);
 }
Ejemplo n.º 55
0
    public void pompa_funkcja()
    {
        var client = new UdpClient();
        IPEndPoint ep = new IPEndPoint(IPAddress.Parse("192.168.42.42"), 8888);
        client.Connect(ep);
        // send data
        Byte[] sendBytes = System.Text.Encoding.ASCII.GetBytes("C");
        client.Send(sendBytes, sendBytes.Length);
        // then receive data
        var receivedData = client.Receive(ref ep);
        string returnData = System.Text.Encoding.ASCII.GetString(receivedData);
        zalaczenie.Text = returnData + "%";

        var client2 = new UdpClient();
        IPEndPoint ep2 = new IPEndPoint(IPAddress.Parse("192.168.42.42"), 8888);
        client.Connect(ep2);
        // send data
        Byte[] sendBytes2 = System.Text.Encoding.ASCII.GetBytes("D");
        client.Send(sendBytes2, sendBytes2.Length);
        // then receive data
        var receivedData2 = client.Receive(ref ep2);
        string returnData2 = System.Text.Encoding.ASCII.GetString(receivedData2);
        wylaczenie.Text = returnData2 + "%";

        var client3 = new UdpClient();
        IPEndPoint ep3 = new IPEndPoint(IPAddress.Parse("192.168.42.42"), 8888);
        client.Connect(ep3);
        // send data
        Byte[] sendBytes3 = System.Text.Encoding.ASCII.GetBytes("E");
        client.Send(sendBytes3, sendBytes3.Length);
        // then receive data
        var receivedData3 = client.Receive(ref ep3);
        string returnData3 = System.Text.Encoding.ASCII.GetString(receivedData3);
        if (returnData3 == "0")
        { tryb.Text = "AUTO"; }
        if (returnData3 == "1")
        { tryb.Text = "ON"; }
        if (returnData3 == "2")
        { tryb.Text = "OFF"; }
    }
Ejemplo n.º 56
0
        private static Server ResolveServer(IPAddress IP, int Port)
        {
            IPEndPoint Endpoint = new IPEndPoint(IP, Port);

            using (UdpClient Client = new UdpClient())
            {
                Client.Client.SendTimeout = Client.Client.ReceiveTimeout = 4000;
                try
                {
                    Client.Connect(Endpoint);
                    byte[] Datagram = new byte[]
                    {
                        0xFF, 0xFF, 0xFF, 0xFF, 0x54, 0x53, 0x6F, 0x75,
                        0x72, 0x63, 0x65, 0x20, 0x45, 0x6E, 0x67, 0x69,
                        0x6E, 0x65, 0x20, 0x51, 0x75, 0x65, 0x72, 0x79, 0x00
                    };
                    Client.Send(Datagram, 25);
                    bool   NS = false;
                    int    MaxPlayers;
                    string Map = string.Empty, Name = string.Empty;
                    using (MemoryStream Reader = new MemoryStream(Client.Receive(ref Endpoint)))
                    {
                        Reader.Position = 6L;
                        int Char;
                        while ((Char = Reader.ReadByte()) != 0)
                        {
                            Name += ToChar(Char);
                        }
                        while ((Char = Reader.ReadByte()) != 0)
                        {
                            Map += ToChar(Char);
                        }
                        while (Reader.ReadByte() != 0)
                        {
                            ;
                        }
                        while (Reader.ReadByte() != 0)
                        {
                            ;
                        }
                        byte[] Buffer = new byte[2];
                        Reader.Read(Buffer, 0, 2);
                        if (ToInt16(Buffer, 0) != 480)
                        {
                            NS = true;
                        }
                        Reader.Position++;
                        MaxPlayers = Reader.ReadByte();
                    }
                    MapCode Code = MapCode.TheIsland;
                    foreach (DLC DLC in DLCs)
                    {
                        if (Map.Contains(DLC.Name))
                        {
                            Code = DLC.Code;
                        }
                    }
                    if (Name.Length > 27)
                    {
                        Name = Name.Substring(0, 27);
                    }
                    return(new Server(IP, NS ? (MapCode)(-1) : Code, Port, Name)
                    {
                        MaxPlayers = MaxPlayers
                    });
                }
                catch { return(null); }
            }
        }
Ejemplo n.º 57
0
 /// <summary>
 /// Creates an instance of RADIUS client for sending request to a RADIUS server.
 /// </summary>
 /// <param name="serverName">Name or address of the RADIUS server.</param>
 /// <param name="serverPort">Port number of the RADIUS server.</param>
 /// <param name="sharedSecret">Shared secret used for encryption and authentication.</param>
 /// <remarks></remarks>
 public RadiusClient(string serverName, int serverPort, string sharedSecret)
 {
     this.SharedSecret = sharedSecret;
     this.RequestAttempts = 1;
     this.ReponseTimeout = 15000;
     this.NewPinModeMessage1 = DefaultNewPinModeMessage1;
     this.NewPinModeMessage2 = DefaultNewPinModeMessage2;
     this.NewPinModeMessage3 = DefaultNewPinModeMessage3;
     this.NextTokenModeMessage = DefaultNextTokenModeMessage;
     m_udpClient = new UdpClient(string.Format("Server={0}; RemotePort={1}; LocalPort=0", serverName, serverPort));
     m_udpClient.ReceiveDataComplete += m_udpClient_ReceivedData;
     m_udpClient.Connect(); // Start the connection cycle.
 }
Ejemplo n.º 58
0
 public void Connect(string host, int port) => _client.Connect(host, port);
 public void Connect()
 {
     _udpClient = new UdpClient();
     _udpClient.Connect(_url, _port);
 }
Ejemplo n.º 60
0
    public void WakeUp(string mac)
    {
        Regex pattern = new Regex("[:]");
        string wolHostMac = pattern.Replace(mac, "");

        try
        {
            long value = long.Parse(wolHostMac, NumberStyles.HexNumber, CultureInfo.CurrentCulture.NumberFormat);
            byte[] macBytes = BitConverter.GetBytes(value);

            Array.Reverse(macBytes);
            byte[] macAddress = new byte[6];

            for (int j = 0; j < 6; j++)
                macAddress[j] = macBytes[j + 2];

            byte[] packet = new byte[17 * 6];

            for (int i = 0; i < 6; i++)
                packet[i] = 0xff;

            for (int i = 1; i <= 16; i++)
            {
                for (int j = 0; j < 6; j++)
                    packet[i * 6 + j] = macAddress[j];
            }

            UdpClient client = new UdpClient();
            client.Connect(IPAddress.Broadcast, 9);
            client.Send(packet, packet.Length);
        }
        catch { }
    }