Beispiel #1
0
        internal static async Task <IPAddress[]> LookupHostName(string hostName)
        {
            try
            {
                IReadOnlyList <EndpointPair> data = await DatagramSocket.GetEndpointPairsAsync(new HostName(hostName), "0").AsTask();

                List <IPAddress> addresses = new List <IPAddress>(data.Count);
                if (data != null && data.Count > 0)
                {
                    foreach (EndpointPair item in data)
                    {
                        if (item != null && item.RemoteHostName != null &&
                            (item.RemoteHostName.Type == HostNameType.Ipv4 || item.RemoteHostName.Type == HostNameType.Ipv6))
                        {
                            IPAddress address;
                            if (IPAddress.TryParse(item.RemoteHostName.CanonicalName, out address))
                            {
                                addresses.Add(address);
                            }
                        }
                    }
                }
                return(addresses.ToArray());
            }
            catch (Exception exception)
            {
                if (RTSocketError.GetStatus(exception.HResult) != SocketErrorStatus.Unknown)
                {
                    throw new SocketException(exception.HResult & 0x0000FFFF);
                }
                throw;
            }
        }
Beispiel #2
0
        public static string ResolveDNS(string remoteHostName)
        {
            if (string.IsNullOrEmpty(remoteHostName))
            {
                return(string.Empty);
            }

            var ipAddress = string.Empty;

            try
            {
                var data = DatagramSocket.GetEndpointPairsAsync(new HostName(remoteHostName), "0").AsTask().Result;

                if (data != null && data.Count > 0)
                {
                    foreach (
                        var item in
                        data.Where(
                            item => item?.RemoteHostName != null && item.RemoteHostName.Type == HostNameType.Ipv4))
                    {
                        return(item.RemoteHostName.CanonicalName);
                    }
                }
            }
            catch (Exception ex)
            {
                ipAddress = ex.Message;
            }

            return(ipAddress);
        }
Beispiel #3
0
        private static async Task <EndpointPair> ResolveDNS(string remoteHostName, int port)
        {
            if (string.IsNullOrEmpty(remoteHostName))
            {
                return(null);
            }

            string ipAddress = string.Empty;

            try
            {
                IReadOnlyList <EndpointPair> data = await DatagramSocket.GetEndpointPairsAsync(new HostName(remoteHostName), port.ToString());

                if (data != null && data.Count > 0)
                {
                    foreach (EndpointPair item in data)
                    {
                        if (item != null && item.RemoteHostName != null && (item.RemoteHostName.Type == HostNameType.Ipv4 || item.RemoteHostName.Type == HostNameType.Ipv6))
                        {
                            return(item);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine(ex);
            }

            return(null);
        }
Beispiel #4
0
        internal long GetId()
        {
            //Check locals
            if (HostName == null)
            {
                return(ParseIpToId("0.0.0.0"));
            }

            if (HostName.DisplayName == "localhost")
            {
                return(ParseIpToId("127.0.0.1"));
            }

            //Check remote
            string hostIp = string.Empty;
            var    task   = DatagramSocket.GetEndpointPairsAsync(HostName, "0").AsTask();

            task.Wait();

            //IPv4
            foreach (var endpointPair in task.Result)
            {
                hostIp = endpointPair.RemoteHostName.CanonicalName;
                if (endpointPair.RemoteHostName.Type == HostNameType.Ipv4)
                {
                    return(ParseIpToId(hostIp));
                }
            }

            //Else
            return(hostIp.GetHashCode() ^ Port);
        }
Beispiel #5
0
        /// <summary>
        /// Determines whether the specified host is reachable.
        /// </summary>
        /// <param name="host">The host.</param>
        /// <param name="timeout">The timeout.</param>
        public async Task <bool> IsReachable(string host, TimeSpan timeout)
        {
            var task = Task.Factory.StartNew <bool>(
                () =>
            {
                if (NetworkInformation.GetInternetConnectionProfile()?.GetNetworkConnectivityLevel() == NetworkConnectivityLevel.None)
                {
                    return(false);
                }

                try
                {
                    var endPointPairListTask = DatagramSocket.GetEndpointPairsAsync(new HostName(host), "0");

                    var endPointPairList = endPointPairListTask.GetResults();

                    var endPointPair = endPointPairList.First();

                    return(true);
                }
                catch (Exception)
                {
                }

                return(false);
            });

            return(await task);
        }
Beispiel #6
0
        /// <summary>
        /// Checks if the specified remote host name exists.
        /// </summary>
        /// <param name="remoteHostName">The remote host name.</param>
        /// <returns>true, if exists; otherwise, false.</returns>
        public static async Task <bool> ResolveDNS(string remoteHostName)
        {
            try
            {
                IReadOnlyList <EndpointPair> data = await DatagramSocket.GetEndpointPairsAsync(new HostName(remoteHostName), "0");

                if (data != null && data.Count > 0)
                {
                    foreach (EndpointPair item in data)
                    {
                        if (item != null &&
                            item.RemoteHostName != null &&
                            item.RemoteHostName.Type == HostNameType.Ipv4)
                        {
                            return(true);
                        }
                    }
                }

                return(false);
            }
            catch
            {
                return(false);
            }
        }
Beispiel #7
0
        public async Task <IpVersion> GetCurrentIpVersion()
        {
            try
            {
                // resolves domain name to IP addresses (may contain several)
                var endPointPairs = await DatagramSocket.GetEndpointPairsAsync(new HostName("google.com"), "0");

                if (endPointPairs == null)
                {
                    return(IpVersion.None);
                }

                // detect which IP version is supported
                var result = IpVersion.None;
                foreach (var endPoint in endPointPairs)
                {
                    if (endPoint.RemoteHostName != null)
                    {
                        if (endPoint.RemoteHostName.Type == HostNameType.Ipv4)
                        {
                            result |= IpVersion.IPv4;
                        }
                        else if (endPoint.RemoteHostName.Type == HostNameType.Ipv6)
                        {
                            result |= IpVersion.IPv6;
                        }
                    }
                }
                return(result);
            }
            catch
            {
                return(IpVersion.None);
            }
        }
Beispiel #8
0
        private static async Task <string> ResolveDNS(string remoteHostName)
        {
            if (string.IsNullOrEmpty(remoteHostName))
            {
                return(string.Empty);
            }

            string ipAddress = string.Empty;

            IReadOnlyList <EndpointPair> data =
                await DatagramSocket.GetEndpointPairsAsync(new HostName(remoteHostName), "0");

            if (data != null && data.Count > 0)
            {
                foreach (EndpointPair item in data)
                {
                    if (item != null && item.RemoteHostName != null &&
                        item.RemoteHostName.Type == HostNameType.Ipv4)
                    {
                        return(item.RemoteHostName.CanonicalName);
                    }
                }
            }

            return(ipAddress);
        }
Beispiel #9
0
        public NetEndPoint(string hostName, int port)
        {
            var task = DatagramSocket.GetEndpointPairsAsync(new HostName(hostName), port.ToString()).AsTask();

            task.Wait();
            HostName = task.Result[0].RemoteHostName;
            Port     = port;
            PortStr  = port.ToString();
        }
Beispiel #10
0
        /// <summary>
        /// Returns the Internet Protocol (IP) addresses for the specified host.
        /// </summary>
        /// <param name="hostNameOrAddress">The host name or IP address to resolve</param>
        /// <returns>
        /// An array of type <see cref="IPAddress"/> that holds the IP addresses for the host that
        /// is specified by the <paramref name="hostNameOrAddress"/> parameter.
        /// </returns>
        /// <exception cref="ArgumentNullException"><paramref name="hostNameOrAddress"/> is <c>null</c>.</exception>
        /// <exception cref="SocketException">An error is encountered when resolving <paramref name="hostNameOrAddress"/>.</exception>
        public static IPAddress[] GetHostAddresses(string hostNameOrAddress)
        {
#if FEATURE_DNS_SYNC
            return(Dns.GetHostAddresses(hostNameOrAddress));
#elif FEATURE_DNS_TAP
            return(Dns.GetHostAddressesAsync(hostNameOrAddress).Result);
#else
            IPAddress address;
            if (IPAddress.TryParse(hostNameOrAddress, out address))
            {
                return new [] { address }
            }
            ;

#if FEATURE_DEVICEINFORMATION_APM
            var resolveCompleted = new ManualResetEvent(false);
            NameResolutionResult nameResolutionResult = null;
            DeviceNetworkInformation.ResolveHostNameAsync(new DnsEndPoint(hostNameOrAddress, 0), result =>
            {
                nameResolutionResult = result;
                resolveCompleted.Set();
            }, null);

            // wait until address is resolved
            resolveCompleted.WaitOne();

            if (nameResolutionResult.NetworkErrorCode == NetworkError.Success)
            {
                var addresses = new List <IPAddress>(nameResolutionResult.IPEndPoints.Select(p => p.Address).Distinct());

                return(addresses.ToArray());
            }
            throw new SocketException((int)nameResolutionResult.NetworkErrorCode);
#elif FEATURE_DATAGRAMSOCKET
            // TODO we may need to only return those IP addresses that are supported on the current system
            // TODO http://wojciechkulik.pl/csharp/winrt-how-to-detect-supported-ip-versions

            var endpointPairs = DatagramSocket.GetEndpointPairsAsync(new HostName(hostNameOrAddress), "").GetAwaiter().GetResult();
            var addresses     = new List <IPAddress>();
            foreach (var endpointPair in endpointPairs)
            {
                if (endpointPair.RemoteHostName.Type == HostNameType.Ipv4 || endpointPair.RemoteHostName.Type == HostNameType.Ipv6)
                {
                    addresses.Add(IPAddress.Parse(endpointPair.RemoteHostName.CanonicalName));
                }
            }
            if (addresses.Count == 0)
            {
                throw new SocketException((int)System.Net.Sockets.SocketError.HostNotFound);
            }
            return(addresses.ToArray());
#else
            throw new NotSupportedException("Resolving hostname to IP address is not implemented.");
#endif // FEATURE_DEVICEINFORMATION_APM
#endif
        }
    }
        public async Task HostToIp(string hostname, Windows.UI.Xaml.Controls.ListView output)
        {
            HostName host = new HostName(hostname);
            var      eps  = await DatagramSocket.GetEndpointPairsAsync(host, "80");

            foreach (EndpointPair ep in eps)
            {
                string result = ep.RemoteHostName.ToString();
                //output.Items.Clear();
                output.Items.Add(result);
            }
        }
        internal static IPAddress GetIPAddress(this string host)
        {
            IPAddress ipAddress;

            if (!IPAddress.TryParse(host, out ipAddress))
            {
                var endpointPairs = DatagramSocket.GetEndpointPairsAsync(new HostName(host), "0").GetResults();
                ipAddress = IPAddress.Parse(endpointPairs[0].RemoteHostName.DisplayName);
            }

            return(ipAddress);
        }
Beispiel #13
0
        async Task OpenAsync()
        {
            Debug.WriteLine("MqttTransportHandler.OpenAsync()");

#if WINDOWS_UWP
            HostName host          = new HostName(this.hostName);
            var      endpointPairs = await DatagramSocket.GetEndpointPairsAsync(host, "");

            var ep = endpointPairs.First();
            this.serverAddress = IPAddress.Parse(ep.RemoteHostName.RawName);
#else
#if !NETSTANDARD1_3
            this.serverAddress = Dns.GetHostEntry(this.hostName).AddressList[0];
#else
            this.serverAddress = (await Dns.GetHostAddressesAsync(this.hostName).ConfigureAwait(false))[0];
#endif
#endif
            if (this.TryStateTransition(TransportState.NotInitialized, TransportState.Opening))
            {
                try
                {
                    this.channel = await this.channelFactory(this.serverAddress, ProtocolGatewayPort).ConfigureAwait(false);
                }
                catch (Exception ex) when(!ex.IsFatal())
                {
                    this.OnError(ex);
                    throw;
                }

                this.ScheduleCleanup(async() =>
                {
                    this.disconnectAwaitersCancellationSource.Cancel();
                    if (this.channel == null)
                    {
                        return;
                    }
                    if (this.channel.Active)
                    {
                        await this.channel.WriteAsync(DisconnectPacket.Instance).ConfigureAwait(false);
                    }
                    if (this.channel.Open)
                    {
                        await this.channel.CloseAsync().ConfigureAwait(false);
                    }
                });
            }

            await this.connectCompletion.Task.ConfigureAwait(false);

            // Codes_SRS_CSHARP_MQTT_TRANSPORT_18_031: `OpenAsync` shall subscribe using the '$iothub/twin/res/#' topic filter
            await this.SubscribeTwinResponsesAsync().ConfigureAwait(false);
        }
Beispiel #14
0
        public override async Task <Connections> GetConnections()
        {
            var remoteHostName = new HostName(remoteHost);
            var endpointList   = await DatagramSocket.GetEndpointPairsAsync(remoteHostName, remoteService);

            var epair = endpointList.First();

            var connections = new Connections {
                new Connection("Server", epair)
            };

            return(connections);
        }
Beispiel #15
0
        private static async Task <string> DnsLookup(string remoteHostName)
        {
            IReadOnlyList <EndpointPair> data = await DatagramSocket.GetEndpointPairsAsync(new HostName(remoteHostName), "0").AsTask().ConfigureAwait(false);

            if (data != null && data.Count > 0)
            {
                foreach (EndpointPair item in data)
                {
                    if (item != null && item.RemoteHostName != null && item.RemoteHostName.Type == HostNameType.Ipv4)
                    {
                        return(item.RemoteHostName.CanonicalName);
                    }
                }
            }
            return(string.Empty);
        }
        internal static bool IsLoopBack(string host)
        {
#if WINRT
            var allAddressesTask = DatagramSocket.GetEndpointPairsAsync(new HostName(host), "0").AsTask();
            allAddressesTask.Wait();
            var allAddresses = allAddressesTask.Result
                               .Where(x => x != null && x.RemoteHostName != null && (x.RemoteHostName.Type == HostNameType.Ipv4 || x.RemoteHostName.Type == HostNameType.Ipv6))
                               .Select(x => x.RemoteHostName)
                               .ToList();
            return(allAddresses.Any(x => x.IsLoopBack()));
#elif SILVERLIGHT || PCL
            return(false);
#else
            return(Dns.GetHostAddresses(host).Any(IPAddress.IsLoopback));
#endif
        }
Beispiel #17
0
        /// <summary>
        /// 测试指定域名是否能够连接
        /// </summary>
        /// <param name="hostname">域名</param>
        /// <returns>能正常连接则返回true</returns>
        public static async Task <bool> TestConnectivity(string hostname)
        {
            try
            {
                HostName host = new HostName(hostname);
                var      eps  = await DatagramSocket.GetEndpointPairsAsync(host, "80");

                return(eps.Count >= 1);
            }
            catch (Exception e)
            {
                System.Diagnostics.Debug.WriteLine("在测试连接性中发生异常");
                System.Diagnostics.Debug.WriteLine(e.Message);
                return(false);
            }
        }
Beispiel #18
0
        private async void Button_Click(object sender, RoutedEventArgs e)
        {
            HostName host = new HostName("www.mail.ru");
            var      eps  = await DatagramSocket.GetEndpointPairsAsync(host, "80");

            if (eps.Count >= 1)
            {
                messageb.Text = eps.Count.ToString() + "\n";
            }
            else
            {
                messageb.Text = "error\n";
            }
            //Ping ping = new Ping();
            // Send a ping.
            //PingReply reply = await ping.SendPingAsync("dotnetperls.com");
            // Display the result.
            //Text.Text = "ADDRESS:" + reply.Address.ToString();
            //Text.Text = Text.Text + "TIME:" + reply.RoundtripTime;
        }
Beispiel #19
0
        public static IPAddress[] GetAddressesByName(string host)
        {
            IReadOnlyList <EndpointPair> data = null;

            try
            {
                Task.Run(async() =>
                {
                    data = await DatagramSocket.GetEndpointPairsAsync(new HostName(host), "0");
                }).Wait();
            }
            catch (Exception ex)
            {
                return(null);
            }

            return(data != null
                ? data.Where(i => i.RemoteHostName.Type == HostNameType.Ipv4).GroupBy(i => i.RemoteHostName.DisplayName)
                   .Select(i => IPAddress.Parse(i.First().RemoteHostName.DisplayName))
                   .ToArray() : null);
        }
Beispiel #20
0
        protected async override void OnNavigatedTo(NavigationEventArgs e)
        {
            base.OnNavigatedTo(e);

            this.displayRequest = new DisplayRequest();
            this.displayRequest.RequestActive();

            var pairs = await DatagramSocket.GetEndpointPairsAsync(new HostName("192.168.4.1"), "4789");

            //if (pairs.Count > 0 && pairs.First().LocalHostName.RawName.Equals("192.168.4.2"))
            // {
            await this.socket.BindServiceNameAsync("4789");

            this.socket.MessageReceived += Socket_MessageReceived;

            await this.socket.ConnectAsync(new HostName("192.168.4.1"), "4789");

            this.dw = new DataWriter(this.socket.OutputStream);

            //}
        }
Beispiel #21
0
        /// <summary>
        /// 测试指定域名是否能够连接
        /// </summary>
        /// <param name="hostname">域名</param>
        /// <returns>能正常连接则返回true</returns>
        public static async Task <bool> TestConnectivity(string hostname)
        {
            try
            {
                HostName host = new HostName(hostname);
                var      eps  = await DatagramSocket.GetEndpointPairsAsync(host, "80");

                if (eps.Count == 0)
                {
                    return(false);
                }

                HttpClient client   = new HttpClient();
                var        response = await client.GetAsync(hostname);

                return(response.IsSuccessStatusCode);
            }
            catch (Exception e)
            {
                LoggingService.Debug("Service", "在测试连接性中发生异常:" + e.Message);
                return(false);
            }
        }
Beispiel #22
0
        public static async Task <IPHostEntry> ResolveDNS(string remoteHostName)
        {
            if (string.IsNullOrEmpty(remoteHostName))
            {
                return(null);
            }

            IPHostEntry result = new IPHostEntry();

            try
            {
                IReadOnlyList <EndpointPair> data =
                    await DatagramSocket.GetEndpointPairsAsync(new HostName(remoteHostName), "0");

                if (data != null && data.Count > 0)
                {
                    result.AddressList = new IPAddress[data.Count];
                    int i = 0;
                    foreach (EndpointPair item in data)
                    {
                        if (item != null && item.RemoteHostName != null &&
                            item.RemoteHostName.Type == HostNameType.Ipv4)
                        {
                            result.AddressList[i] = IPAddress.Parse(item.RemoteHostName.CanonicalName);
                        }
                        i++;
                    }
                }
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine("error resolving dns name {0}. ex:\n{1}", remoteHostName, ex);
                return(null);
            }

            return(result);
        }
        internal static async Task <string> ResolveHost(string host, IPv4SupportLevel supportLevel)
        {
#if WINRT
            var allAddresses = (await DatagramSocket.GetEndpointPairsAsync(new HostName(host), "0"))
                               .Where(x => x != null && x.RemoteHostName != null)
                               .Select(x => x.RemoteHostName)
                               .ToList();
            var addressesIPv4 = allAddresses.Where(x => x.Type == HostNameType.Ipv4)
                                .ToList();
            HostName addr;
            if (supportLevel == IPv4SupportLevel.RequiresIPv4)
            {
                if (addressesIPv4.Count != 0)
                {
                    addr = addressesIPv4[_addressRng.Next(0, addressesIPv4.Count)];
                }
                else
                {
                    addr = null;
                }
            }
            else
            {
                var addressesIPv6 = allAddresses.Where(x => x.Type == HostNameType.Ipv6)
                                    .ToList();
                if (supportLevel == IPv4SupportLevel.NoPreference)
                {
                    addressesIPv6.AddRange(addressesIPv4);
                }
                if (addressesIPv6.Count != 0)
                {
                    addr = addressesIPv6[_addressRng.Next(0, addressesIPv6.Count)];
                }
                else
                {
                    addr = null;
                }
            }
            if (addr == null)
            {
                return(null);
            }
            return(addr.CanonicalName);
#elif SILVERLIGHT || PCL
            return(await Task.Factory.StartNew <string>(() =>
            {
                throw new NotSupportedException();
            }));
#else
            var allAddresses = (await Task.Factory.FromAsync <string, IPAddress[]>(Dns.BeginGetHostAddresses, Dns.EndGetHostAddresses, host, null))
                               .ToList();
            var addressesIPv4 = allAddresses.Where(x => x.AddressFamily == AddressFamily.InterNetwork)
                                .ToList();
            IPAddress addr;
            if (supportLevel == IPv4SupportLevel.RequiresIPv4)
            {
                if (addressesIPv4.Count != 0)
                {
                    addr = addressesIPv4[_addressRng.Next(0, addressesIPv4.Count)];
                }
                else
                {
                    addr = null;
                }
            }
            else
            {
                var addressesIPv6 = allAddresses.Where(x => x.AddressFamily == AddressFamily.InterNetworkV6)
                                    .ToList();
                if (supportLevel == IPv4SupportLevel.NoPreference)
                {
                    addressesIPv6.AddRange(addressesIPv4);
                }
                if (addressesIPv6.Count != 0)
                {
                    addr = addressesIPv6[_addressRng.Next(0, addressesIPv6.Count)];
                }
                else
                {
                    addr = null;
                }
            }
            if (addr == null)
            {
                return(null);
            }
            return(addr.ToString());
#endif
        }
Beispiel #24
0
        public async Task <string[]> ResolveHostname(string hostname)
        {
            IReadOnlyList <EndpointPair> data = await DatagramSocket.GetEndpointPairsAsync(new HostName(hostname), "0");

            return(data.Select(ep => ep.RemoteHostName.DisplayName).ToArray());
        }