/// <summary>
    /// Function for starting the listening for messages.
    /// </summary>
    /// <param name="port">The port to listen on.</param>
    public async void StartSockets(int tcpPort, int udpPort)
    {
        _tcpListener = new StreamSocketListener();
        _tcpListener.Control.KeepAlive   = true;
        _tcpListener.ConnectionReceived += ConnectionReceived;
        _udpSocket = new DatagramSocket();
        _udpSocket.MessageReceived += LeapDataReceived;

        _localHostName = GetIpv4HostName();

        try
        {
            await _tcpListener.BindEndpointAsync(_localHostName, tcpPort.ToString());

            Debug.LogFormat("Bound TCP-socket to endpoint {0}/{1}", _localHostName.ToString(), tcpPort.ToString());
            await _udpSocket.BindEndpointAsync(_localHostName, udpPort.ToString());

            Debug.LogFormat("Bound UDP-socket to endpoint {0}/{1}", _localHostName.ToString(), udpPort.ToString());
            _currentText.Value = "Sockets bound. Ready to calibrate.";
        }
        catch (Exception e)
        {
            Debug.LogException(e);
        }
    }
Esempio n. 2
0
        private void ProcessDeviceDiscoveryMessage(HostName remoteAddress, string remotePort, LifxResponse msg)
        {
            if (DiscoveredBulbs.ContainsKey(remoteAddress.ToString()))                //already discovered
            {
                DiscoveredBulbs[remoteAddress.ToString()].LastSeen = DateTime.UtcNow; //Update datestamp
                return;
            }
            if (msg.Source != discoverSourceID ||                    //did we request the discovery?
                _DiscoverCancellationSource == null ||
                _DiscoverCancellationSource.IsCancellationRequested) //did we cancel discovery?
            {
                return;
            }

            var device = new LightBulb()
            {
                HostName = remoteAddress,
                Service  = msg.Payload[0],
                Port     = BitConverter.ToUInt32(msg.Payload, 1),
                LastSeen = DateTime.UtcNow
            };

            DiscoveredBulbs[remoteAddress.ToString()] = device;
            devices.Add(device);
            if (DeviceDiscovered != null)
            {
                DeviceDiscovered(this, new DeviceDiscoveryEventArgs()
                {
                    Device = device
                });
            }
        }
        /// <summary>
        /// This will monitor various messages and act on them accordingly. Temperature sensor messages are stored in the
        /// variable with DateTime Stamp added. Thus if the datetime stamp is different from current time (10 minutes grace)
        /// then you know the device is not functioning. Intruder Detect also sends INTRUDERALIVE pulse. Though not used
        /// currently, similar methods to be followed for expanding this to all devices, to provide keep alive pulse and
        /// initmate user when it fails. Need to expand across all devices. Left for next version.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="args"></param>
        private async void MessageReceivedAsync(DatagramSocket sender, DatagramSocketMessageReceivedEventArgs args)
        {
            try
            {
                DataReader reader = args.GetDataReader();
                uint       len    = reader.UnconsumedBufferLength;

                RemoteMessage = reader.ReadString(len);
                RemoteAddress = args.RemoteAddress;
                RemotePort    = args.RemotePort;
                //Debug.WriteLine("Remote Message Received from IP: {0} Port: {1} Message: {2}", RemoteAddress.ToString(), RemotePort, RemoteMessage);

                if (RemoteMessage.Contains(Constants.TEMPSENSE))  //10 characters
                {
                    for (int i = 0; i < Constants.ROOMS; i++)
                    {
                        if (RemoteAddress.ToString() == Constants.TemperatureMonitorAddress[i])
                        {
                            temperatureAlerts[i] = "Room " + i + 1 + RemoteMessage + " @ " + DateTime.Now.ToString() + "\n";
                            break;
                        }
                    }
                }
                else
                {
                    if (RemoteMessage.Contains(Constants.INTRUDERDETECT))
                    {
                        Debug.WriteLine(RemoteMessage);
                        RemoteMessage += " @ " + DateTime.Now.ToString();
                        await Task.Run(() => SendEmailAsync(RemoteMessage));
                    }
                    else
                    {
                        if (RemoteMessage.Contains(Constants.INTRUDERALIVE))
                        {
                            for (int i = 0; i < Constants.ROOMS; i++)
                            {
                                if (RemoteAddress.ToString() == Constants.IntruderDetectAddress[i])
                                {
                                    Detectors[i].strAlive = RemoteMessage;
                                    break;
                                }
                            }
                        }
                    }
                }
                reader.Dispose();
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.ToString());
            }
        }
Esempio n. 4
0
        public async Task AccountSASSignedIPs()
        {
            OperationContext opContext = new OperationContext();
            HostName         invalidIP = new HostName("255.255.255.255");

            SharedAccessAccountPolicy policy = GetPolicyWithFullPermissions();

            policy.IPAddressOrRange = new IPAddressOrRange(invalidIP.ToString());

            await TestHelper.ExpectedExceptionAsync((async() => await RunBlobTest(policy, null, opContext)), opContext, "Operation should have failed with invalid IP access.", HttpStatusCode.Forbidden, "AuthorizationFailure");

            await TestHelper.ExpectedExceptionAsync((async() => await RunQueueTest(policy, null, opContext)), opContext, "Operation should have failed with invalid IP access.", HttpStatusCode.Forbidden, "AuthorizationFailure");

            await TestHelper.ExpectedExceptionAsync((async() => await RunFileTest(policy, null, opContext)), opContext, "Operation should have failed with invalid IP access.", HttpStatusCode.Forbidden, "AuthorizationFailure");

            policy.IPAddressOrRange = null;
            await RunBlobTest(policy, null);

            await RunQueueTest(policy, null);

            await RunFileTest(policy, null);

            policy.IPAddressOrRange = new IPAddressOrRange(new HostName("255.255.255.0").ToString(), invalidIP.ToString());

            await TestHelper.ExpectedExceptionAsync((async() => await RunBlobTest(policy, null, opContext)), opContext, "Operation should have failed with invalid IP access.", HttpStatusCode.Forbidden, "AuthorizationFailure");

            await TestHelper.ExpectedExceptionAsync((async() => await RunQueueTest(policy, null, opContext)), opContext, "Operation should have failed with invalid IP access.", HttpStatusCode.Forbidden, "AuthorizationFailure");

            await TestHelper.ExpectedExceptionAsync((async() => await RunFileTest(policy, null, opContext)), opContext, "Operation should have failed with invalid IP access.", HttpStatusCode.Forbidden, "AuthorizationFailure");
        }
Esempio n. 5
0
    private async void Send()
    {
        // get local ip and null checking
        HostName localHostName = GetLocalIp();

        if (localHostName == null)
        {
            return;
        }

        // get local ip string and to IPAddress format
        byte?     prefix        = localHostName.IPInformation.PrefixLength;
        string    localIPString = localHostName.ToString();
        IPAddress localIP       = System.Net.IPAddress.Parse(localIPString);

        // get broadcast address
        string    subnetMaskString = "255.255.255.0"; // TODO: compute subnet mask
        IPAddress subnetIP         = IPAddress.Parse(subnetMaskString);
        IPAddress broadCastIP      = GetBroadcastAddress(localIP, subnetIP);
        HostName  remoteHostname   = new HostName(broadCastIP.ToString());

        // create output
        IOutputStream outputStream = await listenerSocket.GetOutputStreamAsync(remoteHostname, "59105");

        // write command to printer
        using (DataWriter writer = new DataWriter(outputStream)) {
            writer.WriteString("joiner v1");
            await writer.StoreAsync();
        }
    }
Esempio n. 6
0
        //--------------------------------------------------------Set-, Get- Methods:---------------------------------------------------------\\
        #region --Set-, Get- Methods--


        #endregion
        //--------------------------------------------------------Misc Methods:---------------------------------------------------------------\\
        #region --Misc Methods (Public)--
        public async Task ConnectAsync()
        {
            Exception lastException = null;

            for (int i = 1; i <= MAX_CONNECTION_ATTEMPTS; i++)
            {
                try
                {
                    // Setup socket:
                    socket = new StreamSocket();
                    socket.Control.KeepAlive        = true;
                    socket.Control.QualityOfService = SocketQualityOfService.LowLatency;

                    // Connect with timeout:
                    connectTimeoutCTS = new CancellationTokenSource(CONNECTION_TIMEOUT_MS);

                    // Start the connection process:
                    await socket.ConnectAsync(HOSTNAME, PORT.ToString(), SocketProtectionLevel.Tls12).AsTask(connectTimeoutCTS.Token);

                    // Setup stream reader and writer:
                    dataWriter = new DataWriter(socket.OutputStream);
                    dataReader = new DataReader(socket.InputStream)
                    {
                        InputStreamOptions = InputStreamOptions.Partial
                    };
                    return;
                }
                catch (TaskCanceledException e)
                {
                    Logger.Error(LOGGER_TAG + i + " try to connect to " + HOSTNAME.ToString() + " failed:", e);
                    lastException = e;
                }
                catch (Exception e)
                {
                    Logger.Error(LOGGER_TAG + i + " try to connect to " + HOSTNAME.ToString() + " failed:", e);
                    lastException = e;
                }

                if (i < MAX_CONNECTION_ATTEMPTS)
                {
                    // Wait between connection attempts:
                    Logger.Info(LOGGER_TAG + "Starting delay between connection attempts...");
                    await Task.Delay(CONNECTION_ATTEMPT_DELAY);
                }
            }
            throw lastException;
        }
Esempio n. 7
0
 /// <summary>
 /// Initializes a new instance of the CtrlClient class.
 /// </summary>
 /// <param name="hostName">Hostname of the server to connect to.</param>
 /// <param name="port">Port to connect to on the server.</param>
 /// <param name="msgReceivers">Message receivers to dispatch responses from the server.</param>
 /// <param name="statusReceiver">Status receiver for events on this link.</param>
 /// <remarks>
 /// Compat shim does not support control subscriptions.
 /// </remarks>
 public CtrlClient(
     HostName hostName,
     string port,
     List <ICtrlMessageReceiver> msgReceivers,
     ICtrlStatusReceiver statusReceiver) :
     base(hostName.ToString(), port, msgReceivers, null)
 {
     this.statusReceiver = statusReceiver;
 }
Esempio n. 8
0
 public HostNameToken(
     int position,
     int consumedLength,
     HostName hostName)
     : base(
         position,
         consumedLength,
         hostName.ToString())
 {
     this.HostName = hostName;
 }
    private async Task DataListener()
    {
        udpClient = new DatagramSocket();
        udpClient.MessageReceived += Listener_MessageReceived;
        try {
            var      icp = NetworkInformation.GetInternetConnectionProfile();
            HostName IP  = NetworkInformation.GetHostNames().SingleOrDefault(hn =>
                                                                             hn.IPInformation?.NetworkAdapter != null && hn.IPInformation.NetworkAdapter.NetworkAdapterId
                                                                             == icp.NetworkAdapter.NetworkAdapterId);
            Debug.Log("UDPMultiClientMiddleware asking for socket on device: " + IP.ToString());
            await udpClient.BindEndpointAsync(IP, "0");

            _listening = true;
            Debug.Log("UDPMultiClientMiddleware  listening on " + IP.ToString() + ":" + udpClient.Information.LocalPort);
        } catch (Exception e) {
            Debug.Log("DATA LISTENER START EXCEPTION: " + e.ToString());
            Debug.Log(SocketError.GetStatus(e.HResult).ToString());
            return;
        }
    }
Esempio n. 10
0
    async void Start()
    {
        if (udpEvent == null)
        {
            udpEvent = new UDPMessageEvent();
            udpEvent.AddListener(UDPMessageReceived);
        }


        Debug.Log("Waiting for a connection...");

        socket = new DatagramSocket();
        socket.MessageReceived += Socket_MessageReceived;

        HostName IP = null;

        try
        {
            var icp = NetworkInformation.GetInternetConnectionProfile();

            IP = Windows.Networking.Connectivity.NetworkInformation.GetHostNames()
                 .SingleOrDefault(
                hn =>
                hn.IPInformation?.NetworkAdapter != null && hn.IPInformation.NetworkAdapter.NetworkAdapterId
                == icp.NetworkAdapter.NetworkAdapterId);
            Debug.Log("Listening for data in IP" + IP.ToString() + " Port: " + internalPort);
            await socket.BindEndpointAsync(IP, internalPort);
        }
        catch (Exception e)
        {
            Debug.Log(e.ToString());
            Debug.Log(SocketError.GetStatus(e.HResult).ToString());
            return;
        }
        SendUDPMessage(externalIP, externalPort, Encoding.UTF8.GetBytes(IP.ToString()));
    }
Esempio n. 11
0
        /// <summary>
        /// Check if IP of remote user matches any of the lists.
        /// If it exists in blacklist or does not exist in whitelist access is denied.
        /// BlackList allways override the whitelist!
        ///
        /// WhiteList: If no record exist, it's ignored. If atleast one record exists, then we check against the list, else set result to false. If it is found, the return is set to false, else it's set to true.
        /// BlackList: If no record exist do not modify whitelist result. Else, check the IP against the list. If it exists in the list, set the result to true, overriding whatever was result from whitelist.
        /// </summary>
        /// <param name="socket">connectiong socket. we get remote IP address from this.</param>
        /// <returns>True if user should be blocked or false, if access should be granted. Note that this does not override user access verification in any way.</returns>
        public bool ProcessIPFilter(StreamSocket socket)
        {
            // Get remote IP
            HostName remoteHost = socket.Information.RemoteAddress;

            string[] _remoteHostString = remoteHost.ToString().Split('.');
            if (_remoteHostString.Length < 4)
            {
                // IP ni ok. nekaj je treba narediti...
            }
            byte[] _remoteIP = new byte[4];
            for (int i = 0; i < _remoteIP.Length; i++)
            {
                if (!byte.TryParse(_remoteHostString[i], out _remoteIP[i]))
                {
                    // konverzija ni uspela, spet je treba nekaj naredit.
                }
            }

            // process each IP from black and white list. if remote IP is not any of the black lists and if on atleast one white list then return ok, else return true for blocked.
            // 1st check whitelist, then blacklist, so blackist can override whitelist
            bool _result = true;

            if (_whiteList.Count > 0)
            {
                foreach (KeyValuePair <string, IpNumber> key in _whiteList)
                {
                    if (IpInRange(_remoteIP, key.Value))
                    {
                        _result = false;
                    }
                }
            }
            else
            {
                _result = false;
            }

            foreach (KeyValuePair <string, IpNumber> key in _blackList)
            {
                if (IpInRange(_remoteIP, key.Value))
                {
                    _result = true;
                }
            }

            return(_result);
        }
Esempio n. 12
0
            public void Save(WidgetConfig config)
            {
                config["HostName"]       = HostName.ToString();
                config["LogonDomain"]    = LogonDomain.ToString();
                config["IpAddress"]      = IpAddress.ToString();
                config["MachineDomain"]  = MachineDomain.ToString();
                config["MacAddress"]     = MacAddress.ToString();
                config["BootTime"]       = BootTime.ToString();
                config["Cpu"]            = Cpu.ToString();
                config["DefaultGateway"] = DefaultGateway.ToString();
                config["DhcpServer"]     = DhcpServer.ToString();
                config["DnsServer"]      = DnsServer.ToString();
                config["FreeSpace"]      = FreeSpace.ToString();

                config["LabelColor"] = ColorTranslator.ToHtml(LabelColor);
                config["ValueColor"] = ColorTranslator.ToHtml(ValueColor);
            }
        private string GetIPAddress()
        {
            string ipAddress = "Unknown IP";

#if !UNITY_EDITOR && WINDOWS_UWP
            var icp = NetworkInformation.GetInternetConnectionProfile();
            if (icp != null && icp.NetworkAdapter != null)
            {
                HostName localName = NetworkInformation.GetHostNames().FirstOrDefault(n =>
                                                                                      n.Type == HostNameType.Ipv4 &&
                                                                                      n.IPInformation != null &&
                                                                                      n.IPInformation.NetworkAdapter != null &&
                                                                                      n.IPInformation.NetworkAdapter.NetworkAdapterId == icp.NetworkAdapter.NetworkAdapterId);
                if (localName != null)
                {
                    ipAddress = localName.ToString();
                }
            }
#endif
            return(ipAddress);
        }
Esempio n. 14
0
        /// <summary>
        /// Handles Message received from the NodeMCU device. Currently not used. Left for future implementation
        /// </summary>
        /// <param name="sender">DatagramSocket</param>
        /// <param name="args">Contains received information, IP address and port</param>
        private void MessageReceived(DatagramSocket sender, DatagramSocketMessageReceivedEventArgs args)
        {
            DataReader reader = args.GetDataReader();
            uint       len    = reader.UnconsumedBufferLength;

            RemoteMessage = reader.ReadString(len);
            RemoteAddress = args.RemoteAddress;
            RemotePort    = args.RemotePort;
            Debug.WriteLine("Remote Message Received from IP: {0} Port: {1} Message: {2}", RemoteAddress.ToString(), RemotePort, RemoteMessage);
        }
Esempio n. 15
0
 public bool Equals(HostName other)
 {
     return(other.ToString().Equals(TvAddress));
 }
    async void Start()
    {
        BuildMyStructureNew();



        Debug.Log("Waiting for a connection...");

        socket = new DatagramSocket();
        socket.MessageReceived += Socket_MessageReceived;

        HostName IP = null;

        try
        {
            var icp = NetworkInformation.GetInternetConnectionProfile();

            Console3D.Instance.LOGit("icp.netadaptor id = " + icp.NetworkAdapter.NetworkAdapterId.ToString());

            IP = Windows.Networking.Connectivity.NetworkInformation.GetHostNames()
                 .SingleOrDefault(
                hn =>
                hn.IPInformation?.NetworkAdapter != null && hn.IPInformation.NetworkAdapter.NetworkAdapterId
                == icp.NetworkAdapter.NetworkAdapterId);
            Console3D.Instance.LOGit("not even using gamesettings -> my socket is = " + IP.ToString() + " " + internalPort);
            await socket.BindEndpointAsync(IP, internalPort);
        }
        catch (Exception e)
        {
            Debug.Log(e.ToString());
            Debug.Log(SocketError.GetStatus(e.HResult).ToString());
            return;
        }
        //SendUDPMessage(externalIP, externalPort, Encoding.UTF8.GetBytes(PingMessage));
    }
 public SocksAddress(HostName address, int port)
 {
     Port         = port;
     Host         = address.ToString();
     HostNameType = address.GetHostNameType();
 }