Esempio n. 1
0
        public async Task SendMagicPacket(string hostName, int destPort, string targetMac)
        {
            if (!_initialized)
            {
                _client = new UdpSocketClient();
            }

            //turn MAC into an array of bytes
            targetMac = targetMac.Replace("-", "").Replace(":", "");
            byte[] macBytes = Enumerable.Range(0, targetMac.Length)
                              .Where(x => x % 2 == 0)
                              .Select(x => Convert.ToByte(targetMac.Substring(x, 2), 16)) //16 == hexadecimal
                              .ToArray();
            //Magic packet header
            List <byte> magicPacket = new List <byte> {
                0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF
            };

            //Magic packet is the header + the target MACx16
            for (int i = 0; i < 16; i++)
            {
                magicPacket = magicPacket.Concat(macBytes).ToList();
            }

            await _client.SendToAsync(magicPacket.ToArray(), hostName, destPort);
        }
 /////////////////////////////////////////////////////////////////////////////
 //Socket application
 //Socket operation code area start
 //Do not Change IP address and Port number!
 /////////////////////////////////////////////////////////////////////////////
 public static void ConnectClick()
 {
     UdpSocketClient.InitSocket();
     Local_delay();
     DynaLinkHS.SocketDataLogic();
     DynaLinkHS.CmdInitOp(0x01);//Init Net work request
     print("UDP port OPEN");
 }
Esempio n. 3
0
        public UdpSocketClientPage()
        {
            _client      = new UdpSocketClient();
            _messagesSub = new Subject <Message>();
            _messagesObs = _messagesSub.AsObservable();

            InitView();
        }
Esempio n. 4
0
        Socket _socket; //= new Socket(ipAddress.AddressFamily,SocketType.Stream, ProtocolType.Tcp);


        public int FindOpenPort(int start, int end)
        {
            int  port  = start;
            bool found = false;


            while (port <= end)
            {
                UdpSocketClient tClient = new UdpSocketClient();

                byte[] portData = Encoding.ASCII.GetBytes(port.ToString());

                client.SendToAsync(portData, this.sendsTo, this.sendsOn);
                Console.WriteLine("Sending " + port);

                try
                {
                    // convert our greeting message into a byte array
                    var msgBytes = Encoding.UTF8.GetBytes(port.ToString());

                    System.Net.IPEndPoint RemoteIpEndPoint   = new System.Net.IPEndPoint(System.Net.IPAddress.Any, port);
                    UdpClient             receivingUdpClient = new UdpClient(RemoteIpEndPoint);

                    try
                    {
                        // Blocks until a message returns on this socket from a remote host.
                        Byte[] receiveBytes = receivingUdpClient.Receive(ref RemoteIpEndPoint);

                        string returnData = Encoding.ASCII.GetString(receiveBytes);

                        string messageOut = String.Format("[{0},{1}]@[{2}]: {3}",
                                                          RemoteIpEndPoint.Address.ToString(),
                                                          RemoteIpEndPoint.Port.ToString(),
                                                          DateTime.Now,
                                                          returnData.ToString());

                        Console.WriteLine(messageOut);
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine(ex.ToString());
                    }
                }
                catch { }
                finally
                {
                    tempSockets.Add(tClient);
                }
                port++;
                System.Threading.Thread.Sleep(100);
            }

            if (!found)
            {
                return(-1);
            }
            return(port);
        }
Esempio n. 5
0
        public async Task Send(byte[] data, int bytes, IPEndPoint remoteHost)
        {
            var client = new UdpSocketClient();
            await client.SendToAsync(data, remoteHost.Address, remoteHost.Port);

            System.Console.WriteLine(System.DateTime.Now.ToString() + ">>> " + remoteHost);
            System.Console.WriteLine(FormatterHelper.Deserialize(data).ToString());
            System.Console.WriteLine();
        }
Esempio n. 6
0
        private static async void UdpClient()
        {
            var udpClient = new UdpSocketClient();

            var helloWorld = "Hello World!";

            var bytes = Encoding.UTF8.GetBytes(helloWorld);
            await udpClient.SendToAsync(bytes, bytes.Length, address : "192.168.1.5", port : 1234);
        }
Esempio n. 7
0
        //constructor
        public BaseStation(int mPortNum, bool mForwardAll = false, ILogger mLogger = null)
        {
            this.knownPeers = new List <Peer>();
            this.senderUDP  = new UdpSocketClient();
            this.logger     = mLogger;

            this.forwardAll = mForwardAll;
            this.portNum    = mPortNum;
        }
    IEnumerator WaitTime()
    {
        yield return(new WaitForSeconds(0.8f));

        //Must wait 0.8 sec befor close the UDP connection.
        DynaLinkHS.CoreThreadLoopBit = false;
        UdpSocketClient.SocketQuit();
        print("UDP port Closed Sucess");
    }
Esempio n. 9
0
        public async Task <bool> SendBroadcast(string message, string address, int port = 52112)
        {
            byte[] bytes            = Encoding.UTF8.GetBytes(message);
            var    udpSockectClient = new UdpSocketClient();
            await udpSockectClient.SendToAsync(bytes, address, port);

            //await udpSockectClient.SendAsync(bytes);
            return(true);
        }
Esempio n. 10
0
        public async Task SendMessage(string address, int port, string message)
        {
            var client = new UdpSocketClient();

            var msgBytes = Encoding.UTF8.GetBytes(message);

            await client.SendToAsync(msgBytes, address, port);

            client.MessageReceived += Client_MessageReceived;
        }
Esempio n. 11
0
 public async void UDPClientAsync(String botonPresionado)
 {
     var port    = 11000;
     var address = "192.168.137.1";
     var client  = new UdpSocketClient();
     // convert our greeting message into a byte array
     var msgBytes = Encoding.UTF8.GetBytes(botonPresionado);
     // send to address:port, no guarantee that anyone is there  or that the message is delivered.
     await client.SendToAsync(msgBytes, address, port);
 }
        public WifiScanViewModel(INavigationService navigation) : base(navigation)
        {
            Devices          = new ObservableCollection <string>();
            wifiManager      = DependencyService.Get <IWiFiManager>();
            IsPairing        = false;
            Connect          = new Command(StartConnect);
            Title            = IoTCentral.Current.Device.Name;
            ProgressText     = "Searching for compatible devices...";
            PairingCompleted = false;
            PairingResult    = new Result();
            MessagingCenter.Subscribe <IWiFiManager, string>(this, "FOUND", async(manager, ssid) =>
            {
                Associate(ssid);
                await Pair();
            });
            MessagingCenter.Subscribe <IWiFiManager, string>(this, "REGISTERED", async(manager, msg) =>
            {
                var ssid = msg.Split(':')[0];
                if (ssid.Equals(deviceName, StringComparison.CurrentCultureIgnoreCase))
                {
                    ProgressText        = $"Device registered on the network with ip: {msg.Split(':')[1]}";
                    PairingResult.Text  = ((char)0x2713).ToString();
                    PairingResult.Color = Color.Green;
                }
                else
                {
                    ProgressText        = $"Failed to register device";
                    PairingResult.Text  = "X";
                    PairingResult.Color = Color.Red;
                }
                PairingCompleted = true;
                OnPropertyChanged("ProgressText");
                OnPropertyChanged("PairingCompleted");
                OnPropertyChanged("PairingResult");

                //await Navigation.NavigateTo(new DeviceViewModel(Navigation));
            });
            WiFIInstruction = ImageSource.FromResource("iotc_xamarin_ble.Resources.wifi_2.jpg");
            udpClient       = new UdpSocketClient();
            udpReceiver     = new UdpSocketReceiver();
            skipScan        = false;
            if (Device.RuntimePlatform == Device.iOS)
            {
                IsiOS = true;
                ((App)App.Current).ApplicationResumed += ResumeWifi;
            }
        }
Esempio n. 13
0
        public async Task sendBroadcastUdp(string message, int port = 1234)
        {
            byte[] data    = Encoding.UTF8.GetBytes(message);
            string address = "255.255.255.255";

            try
            {
                var uc = new UdpSocketClient();
                await uc.SendToAsync(data, address, port);

                uc.Dispose();
                Debug.WriteLine("UDP: Sent {0} to {1}:{2}", message, address, port);
            }
            catch (Exception e)
            {
                Debug.WriteLine(e.Message);
            }
        }
Esempio n. 14
0
        protected override async void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);
            Xamarin.Essentials.Platform.Init(this, savedInstanceState);
            SetContentView(Resource.Layout.activity_main);

            //UI Elemente suchen
            Button            button1            = FindViewById <Button>(Resource.Id.button1);
            TextInputEditText textInputEditText1 = FindViewById <TextInputEditText>(Resource.Id.textInputEditText1);

            //IP-Adresse laden
            retrieveset();

            //Übergeben Uri überprüfen
            Uri    uri    = Intent.Data;
            string uriStr = "";

            //Falls Uri nicht leer --> Sende Uri und schließe danach
            if (uri != null)
            {
                uriStr = uri.ToString();
                //UDP Senden
                var port     = 15000;
                var address  = textInputEditText1.Text;
                var client   = new UdpSocketClient();
                var msgBytes = Encoding.UTF8.GetBytes(uriStr);

                await client.SendToAsync(msgBytes, address, port);

                RunOnUiThread(() => Toast.MakeText(this, "Link gesendet!", ToastLength.Long).Show());

                Finish();
            }
            //Ansonsten --> bleibe offen
            else
            {
                //Button Klick --> Acitivity schließen
                button1.Click += delegate {
                    saveset();
                    Finish();
                };
            }
        }
Esempio n. 15
0
        /// <summary>
        /// Connect to a client
        /// </summary>
        public async Task <bool> ConnectAsync(string ip, int port)
        {
            try
            {
                // if you need a duplex TCP sample, take a look at SmartHome sample
                socketClient = new UdpSocketClient();
                socketClient.MessageReceived += SocketClient_MessageReceived;
                Serializer = new ProtobufNetworkSerializer();
                await socketClient.ConnectAsync(ip, port);

                StartSendingKeepAlive();
                Connected = true;
            }
            catch (Exception)
            {
                return(false);
            }
            return(true);
        }
Esempio n. 16
0
        public async void Start()
        {
            if (connected)
            {
                return;
            }
            connected = true;

            receiver     = new UdpSocketMulticastClient();
            receiver.TTL = 5;

            sender = new UdpSocketClient();

            receiver.MessageReceived += async(sender, args) =>
            {
                var data = Encoding.UTF8.GetString(args.ByteData, 0, args.ByteData.Length);

                if (data.Equals("INTERACT ID REQUEST"))
                {
                    var stream = new MemoryStream();
                    var writer = new BinaryWriter(stream, Encoding.UTF8);
                    writer.Write((Byte)NetworkMessage.Acknowledge);
                    writer.Write(Properties.Settings.Default.ServerName);
                    writer.Write(Properties.Settings.Default.NetworkToken);
                    writer.Write((Byte)NetworkMessage.EndOfMessage);
                    writer.Flush();

                    await this.sender.SendToAsync(stream.GetBuffer(), args.RemoteAddress, Constants.UdpPort);
                }
            };

            try
            {
                await receiver.JoinMulticastGroupAsync(Constants.MulticastAddress, Constants.MulticastPort);

                Byte[] data = Encoding.ASCII.GetBytes("ANOUNCE SERVER");
                await receiver.SendMulticastAsync(data);
            } catch (Exception e)
            {
                Log.Log.Handle.AddEntry("Error: " + e.Message);
            }
        }
Esempio n. 17
0
        private void init(TouchData apSsid, TouchData apBssid, TouchData apPassword, ITouchEncryptor encryptor, IEsptouchTaskParameter parameter)
        {
            Debug.WriteLine($"Welcome Esptouch {ESPTOUCH_VERSION}");

            mEncryptor  = encryptor;
            mApSsid     = apSsid.getData();
            mApPassword = apPassword.getData();
            mApBssid    = apBssid.getData();

            mIsCancelled = false;

            mSocketClient = new UdpSocketClient();
            mParameter    = parameter;

            mSocketServer = new UdpSocketServer(mParameter.PortListening,
                                                mParameter.WaitUdpTotalMillisecond);

            mEsptouchResultList   = new List <EsptouchResult>();
            mBssidTaskSucCountMap = new Dictionary <string, int>();
        }
Esempio n. 18
0
        private static async Task <List <string> > BroadcastUDP(string ipAddress)
        {
            const int UDP_TIMEOUT_MS = 4000;

            using (var client = new UdpSocketClient())
            {
                var msg     = Encoding.UTF8.GetBytes("SoundBox");
                var replies = new List <string>();
                var port    = int.Parse(SoundBoxServer.TCP_SERVER_PORT);

                AutoResetEvent repliedEvent = new AutoResetEvent(false);

                client.MessageReceived += new EventHandler <UdpSocketMessageReceivedEventArgs>(
                    delegate(object sender, UdpSocketMessageReceivedEventArgs args)
                {
                    var reply = Encoding.UTF8.GetString(args.ByteData, 0, args.ByteData.Length);
                    var tab   = Convert.ToChar(9);
                    if (reply.Contains("SoundBox" + tab))
                    {
                        var parts = reply.Split(tab);
                        if (!replies.Contains(parts[1]))
                        {
                            replies.Add(parts[1]);
                        }
                    }

                    repliedEvent.Set();
                });

                // unusual! overcomes problem in limitation?
                await client.SendToAsync(msg, ipAddress, port);

                await client.ConnectAsync(ipAddress, port);

                await client.SendAsync(msg);

                repliedEvent.WaitOne(TimeSpan.FromMilliseconds(UDP_TIMEOUT_MS));

                return(replies);
            }
        }
Esempio n. 19
0
 public CameraView()
 {
     _lastSent     = DateTime.Now;
     _client       = new UdpSocketClient();
     PreviewReady += HandlePreviewReady;
 }
Esempio n. 20
0
        private static async Task <string> StartDiscovery(Action <List <ServerData> > onServerDiscovered, string ipAddr)
        {
            //if (transmitSocket == null && receiveSocket == null)
            //{

            transmitSocket = new UdpSocketClient();
            string addr = string.Empty;

            receiveSocket.MessageReceived += (sender, args) =>
            {
                var fromIp = args.RemoteAddress;
                var data   = args.ByteData;
                LocalRemoteHostInfo payload;
                try
                {
                    payload = Helpers.Deserialize <LocalRemoteHostInfo>(Encoding.UTF8.GetString(data, 0, data.Length));
                }
                catch (Exception e)
                {
                    Debug.WriteLine(
                        string.Format("Caught {0} while attempting to deserialize local discovery response", e));
                    return;
                }
                var id = payload.LocalNoahServerGuid;
                if (!string.Equals(id, ServerId, StringComparison.CurrentCultureIgnoreCase))
                {
                    return;
                }
                if (serverList.Count > 0)
                {
                    var server = serverList.Find(element => element.FriendlyName == payload.FriendlyName);
                    if (server == null)
                    {
                        serverList.Add(new ServerData
                        {
                            FriendlyName = payload.FriendlyName,
                            RemoteHostId = payload.RemoteHostId,
                            ServerName   = payload.HostName,
                            ServerIp     = payload.LocalHostIpAddress
                        });
                    }
                }
                else
                {
                    serverList.Add(new ServerData
                    {
                        FriendlyName = payload.FriendlyName,
                        RemoteHostId = payload.RemoteHostId,
                        ServerName   = payload.HostName,
                        ServerIp     = payload.LocalHostIpAddress
                    });
                }
                if (addr.Equals("255.255.255.255"))
                {
                    var server = serverList.First(element => element.FriendlyName == payload.FriendlyName);
                    if (server == null)
                    {
                        serverList.Add(new ServerData
                        {
                            FriendlyName = payload.FriendlyName,
                            RemoteHostId = payload.RemoteHostId,
                            ServerName   = payload.HostName,
                            ServerIp     = payload.LocalHostIpAddress
                        });
                    }
                    onServerDiscovered(serverList);
                }
            };
            for (int i = 3; i >= 0;)
            {
                addr = GetBroadcastAddress(ipAddr, i);
                await transmitSocket.SendToAsync(DiscoveryMessage, addr, TxPort);

                i = i - 1;
            }
            return(ipAddr);
            //}
        }
        public PacketsPage()
        {
            InitializeComponent();

            tcpPort = SettingsPage.TCPPort;
            udpPort = SettingsPage.UDPPort;

            tcpServer = new TcpSocketListener();
            udpServer = new UdpSocketReceiver();

            tcpServer.ConnectionReceived += TcpConnection;
            udpServer.MessageReceived    += UdpConnection;

            Task.Run(async() =>
            {
                await tcpServer.StartListeningAsync(tcpPort);
                await udpServer.StartListeningAsync(udpPort);
                SettingsPage.TCPPort = tcpServer.LocalPort;

                MessagingCenter.Send(this, Events.BOUND_PORTS_CHANGED, 0);
            });


            //udpServer.StartListeningAsync(udpPort);

            /*
             += async (sender, args) =>
             * {
             * var client = args.SocketClient;
             *
             * var bytesRead = -1;
             * var buf = new byte[1];
             *
             * while (bytesRead != 0)
             * {
             *  bytesRead = await args.SocketClient.ReadStream.ReadAsync(buf, 0, 1);
             *  //if (bytesRead > 0)
             *  //    Debug.Write(buf[0]);
             * }
             * };
             */

            _connection = DependencyService.Get <ISQLiteDb>().GetConnection();

            /*
             *          var demopackets = Packet.GetDemoPackets();
             * for (int i = 0; i < demopackets.Count(); i++) {
             *  _thepackets.Add(demopackets[i]);
             * }
             *          packetListView.ItemsSource = _thepackets;
             */


            tcp       = new TcpSocketClient();
            udp       = new UdpSocketClient();
            thepacket = new Packet();

            MessagingCenter.Subscribe <LoginPage, List <Packet> >(this, Events.NEW_PACKET_LIST, OnNewPacketListAsync);
            MessagingCenter.Subscribe <ImportCloud, List <Packet> >(this, Events.NEW_PACKET_LIST, OnNewPacketListAsyncIC);
            MessagingCenter.Subscribe <PacketEditPage, Packet>(this, Events.PACKET_MODIFIED, OnPacketModified);
        }
Esempio n. 22
0
 public OscSender()
 {
     sender = new UdpSocketClient();
 }
Esempio n. 23
0
        async public static Task <ServerList> BrowseForNoahServers(string friendlyName, string ipAddress)
        {
            var client   = new UdpSocketClient();
            var receiver = new UdpSocketReceiver();

            try
            {
                var address = GetIpAddressForBroadcast(ipAddress);
                //// convert our greeting message into a byte array
                string clientGUID        = "{B0BE0E7D-F70B-40BE-91AB-14125863B0B7}";
                System.Text.Encoding enc = System.Text.Encoding.UTF8;
                byte[] sendBuffer        = enc.GetBytes(clientGUID);

                receiver.MessageReceived += (sender, args) =>
                {
                    try
                    {
                        var from   = String.Format("{0}:{1}", args.RemoteAddress, args.RemotePort);
                        var fromIp = args.RemoteAddress;
                        var data   = Encoding.UTF8.GetString(args.ByteData, 0, args.ByteData.Length);

                        try
                        {
                            LocalRemoteHostInfo payload =
                                Helpers.Deserialize <LocalRemoteHostInfo>(Encoding.UTF8.GetString(args.ByteData, 0,
                                                                                                  args.ByteData.Length));
                            string guid = payload.LocalNoahServerGuid;
                            if (guid.Equals("{5FE140D5-1D3F-4E46-8892-15FA89DAE9F4}"))
                            {
                                bool duplicate = false;
                                foreach (ServerData servData in ServerCollection)
                                {
                                    if (servData.ServerIp.Equals(fromIp))
                                    {
                                        duplicate = true; //The adress is allready in the list
                                        break;
                                    }
                                }
                                if (duplicate == false) //No need to list Gatteway IP
                                {
                                    if (string.IsNullOrEmpty(friendlyName))
                                    {
                                        ServerCollection.Add(new ServerData
                                        {
                                            ServerName   = payload.HostName,
                                            FriendlyName = payload.FriendlyName,
                                            ServerIp     = payload.LocalHostIpAddress,
                                            RemoteHostId = payload.RemoteHostId
                                        });
                                    }
                                    else
                                    {
                                        if (friendlyName == payload.FriendlyName)
                                        {
                                            receiver.StopListeningAsync();
                                            ServerCollection.Add(new ServerData
                                            {
                                                ServerName   = payload.HostName,
                                                FriendlyName = payload.FriendlyName,
                                                ServerIp     = payload.LocalHostIpAddress,
                                                RemoteHostId = payload.RemoteHostId
                                            });

                                            //client.Dispose();
                                            //receiver.Dispose();
                                            waitTime = false;
                                        }
                                    }
                                }
                            }
                        }
                        catch { }
                    }
                    catch { }
                };
                try
                {
                    receiver.StartListeningAsync(listenPort);
                }
                catch (Exception e)
                {
                }
                client.ConnectAsync(address, port);
                client.SendAsync(sendBuffer);

                DateTime now  = DateTime.Now;
                DateTime stop = now + new TimeSpan(0, 0, 0, 5);


                while (waitTime)
                {
                    if (DateTime.Now > stop)
                    {
                        waitTime = false;
                    }
                }
            }
            catch (Exception e)
            {
                Log.ErrorFormat("Himsa.Noah.MobileAccessLayer.NoahServerUdpBrowser::BrowseForNoahServers(): {0}", e);
                throw;
            }
            finally
            {
                client.DisconnectAsync();
                receiver.StopListeningAsync();
                receiver.Dispose();
            }

            return(new ServerList
            {
                Servers = ServerCollection.ToArray()
            });
        }