private void OnHostResolved(NameResolutionResult result)
        {
            IPEndPoint[] endpoints = result.IPEndPoints;

            System.Windows.Deployment.Current.Dispatcher.BeginInvoke(() =>
            {
                prsBar.Visibility = Rsc.Collapsed;

                if (endpoints == null)
                {
                    MessageBox.Show("Host can not be resolved!\n\nTIP: Even 4-5 tries may be required...");
                }
                else
                {
                    string sCustRes = "";

                    foreach (IPEndPoint ipep in endpoints)
                    {
                        byte[] ipa = ipep.Address.GetAddressBytes();

                        sCustRes = ipa[0].ToString() + "." + ipa[1].ToString() + "."
                                   + ipa[2].ToString() + "." + ipa[3].ToString();

                        //LAST value is the good one...
                        //break;
                    }

                    DoOk(sCustRes);
                }
            });
        }
Example #2
0
        private void OnHostResolved(NameResolutionResult result)
        {
            string sRes = "";

            IPEndPoint[] endpoints = result.IPEndPoints;
            if (endpoints == null)
            {
                sRes = "NOT FOUND";
            }
            else
            {
                foreach (IPEndPoint ipep in endpoints)
                {
                    byte[] ipa = ipep.Address.GetAddressBytes();
                    sRes += "(" + ipa[0].ToString() + "." + ipa[1].ToString() + "."
                            + ipa[2].ToString() + "." + ipa[3].ToString() + ")";
                }
            }

            System.Windows.Deployment.Current.Dispatcher.BeginInvoke(() =>
            {
                txIP.Text = sRes;

                //MessageBox.Show("OnHostResolved called!", "Warning", MessageBoxButton.OK);
            });
        }
Example #3
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
        }
    }
    private void OnNameResolved(NameResolutionResult result)
    {
        IPEndPoint[] endpoints = result.IPEndPoints;
        var          args      = new DnsLookupCompletedEventArgs(endpoints);

        if (DnsLookupCompleted != null)
        {
            DnsLookupCompleted(this, args);
        }
    }
Example #5
0
        /// <summary>
        /// Synchronously resolves hostnames
        /// </summary>
        public static NameResolutionResult ResolveHostname(DnsEndPoint endpoint)
        {
            AutoResetEvent       signal = new AutoResetEvent(false);
            NameResolutionResult nameResolutionResult = null;

            DeviceNetworkInformation.ResolveHostNameAsync(endpoint, (result) =>
            {
                nameResolutionResult = result;
                signal.Set();
            }, null);

            signal.WaitOne();
            return(nameResolutionResult);
        }
        private void OnNameResolved(NameResolutionResult result)
        {
            if (result.NetworkErrorCode == NetworkError.Success)
            {
                IPEndPoint[] endpoints = result.IPEndPoints;
                IPAddress    address   = endpoints[0].Address;

                int port = GetPortFromAddress(address);
                System.Diagnostics.Debug.WriteLine(port);
                string url = "http://sandstorm.case.edu:" + port;

                var client = new WebClient();
                client.DownloadStringCompleted += client_DownloadStringCompleted;
                client.DownloadStringAsync(new Uri(url + "/peerlist"));
            }
        }
Example #7
0
        private void DnsResolutionCallback(NameResolutionResult result)
        {
            if (result.NetworkErrorCode == NetworkError.Success)
            {
                IPAddress[] ipAddresses = new IPAddress[result.IPEndPoints.Length];

                for (int i = 0; i < result.IPEndPoints.Length; i++)
                {
                    ipAddresses[i] = result.IPEndPoints[i].Address;
                }

                OnDnsResolved(true, ipAddresses);

            }
            else
            {
                OnDnsResolved(false, null);
            }
        }
Example #8
0
 private void OnNameResolved(NameResolutionResult result)
 {
     this.ipEndpoint = result.IPEndPoints.First();
 }
Example #9
0
 private void OnNameResolved(NameResolutionResult result)
 {
     this.ipEndpoint = result.IPEndPoints.First();
 }
			private void OnNameResolved(NameResolutionResult dnsResult) {
				if (dnsResult.NetworkInterface == null) {
					if (filestream != null) {
						filestream.Close();
					}
					ctx.Post(result => {
						this.OnError(new ErrorEventArgs(new DownloadException("Network not available")));
					}, null);
					return;
				}

				HttpWebRequest request = (HttpWebRequest)WebRequest.CreateHttp(uri);
				request.Method = "GET";

				Logger.log("DownloadRequestHandler", "Downloading " + uri.AbsoluteUri + " asynchronously...");

				request.BeginGetResponse(async callbackResult => {
					DownloadFile df = (DownloadFile)callbackResult.AsyncState;

					try {
						HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(callbackResult);
						Logger.log("DownloadRequestHandler", "Status: " + (int)response.StatusCode + " " + response.StatusDescription);
						if (response.Headers["Content-Length"] != null) {
							Logger.log("DownloadRequestHandler", "Content length: " + response.Headers["Content-Length"]);
						} else {
							Logger.log("DownloadRequestHandler", "Content length: unknown");
						}

						Stream responseStream = response.GetResponseStream();
						BinaryReader br = new BinaryReader(responseStream);
						int responseBufferSize = 4096;
						int responseBytesRead = 0;
						int responseTotalBytesRead = 0;
						byte[] responseBuffer = new byte[responseBufferSize];

						while ((responseBytesRead = br.Read(responseBuffer, 0, responseBuffer.Length)) > 0) {
							responseTotalBytesRead += responseBytesRead;
							await filestream.WriteAsync(responseBuffer, 0, responseBuffer.Length);
						}
						filestream.Close();

						Logger.log("DownloadRequestHandler", "Wrote " + responseTotalBytesRead + " bytes");

						ctx.Post(result => {
							df.OnComplete((DownloadFileEventArgs)result);
						}, new DownloadFileEventArgs(filestream.Name, responseTotalBytesRead));

					} catch (WebException ex) {
						DownloadException de;
						// check if we have an expired or self-signed cert
						if (ex.Status == WebExceptionStatus.UnknownError) {
							if (ex.Response.Headers.Count == 0 && uri.Scheme == "https") {
								de = new DownloadException("Invalid SSL certificate, returning a 400 Bad Request");
							} else {
								de = new DownloadException("File not found, returning a 404");
							}
						} else {
							de = new DownloadException("400 Bad Request: " + ex.Status.ToString());
						}
						if (filestream != null) {
							filestream.Close();
						}
						ctx.Post(result => {
							df.OnError(new ErrorEventArgs(de));
						}, null);
						Logger.log("DownloadRequestHandler", de.Message);
					}
				}, this);
			}
Example #11
0
        public static Socket ConnectToSocks5Proxy(Socket s, string proxyAdress, ushort proxyPort, string destAddress, ushort destPort, string userName, string password)
        {
            IPAddress destIP   = null;
            IPAddress proxyIP  = null;
            var       request  = new byte[256];
            var       response = new byte[256];
            ushort    nIndex;

            try
            {
                proxyIP = IPAddress.Parse(proxyAdress);
            }
            catch (FormatException)
            {    // get the IP address
                NameResolutionResult resolutionResult = null;
                var dnsResolveEvent = new AutoResetEvent(false);
                var endpoint        = new DnsEndPoint(proxyAdress, 0);
                DeviceNetworkInformation.ResolveHostNameAsync(endpoint, result =>
                {
                    resolutionResult = result;
                    dnsResolveEvent.Set();
                }, null);
                dnsResolveEvent.WaitOne();
                proxyIP = resolutionResult.IPEndPoints[0].Address;
            }

            // Parse destAddress (assume it in string dotted format "212.116.65.112" )
            try
            {
                destIP = IPAddress.Parse(destAddress);
            }
            catch (FormatException)
            {
                // wrong assumption its in domain name format "www.microsoft.com"
            }

            var proxyEndPoint = new IPEndPoint(proxyIP, proxyPort);

            // open a TCP connection to SOCKS server...
            var connected = Connect(s, proxyEndPoint);

            if (!connected)
            {
                throw new ConnectionException("Can't connect to proxy server.");
            }

            nIndex            = 0;
            request[nIndex++] = 0x05; // Version 5.
            request[nIndex++] = 0x02; // 2 Authentication methods are in packet...
            request[nIndex++] = 0x00; // NO AUTHENTICATION REQUIRED
            request[nIndex++] = 0x02; // USERNAME/PASSWORD

            Send(s, request, 0, nIndex);
            var nGot = Receive(s, response, 0, response.Length);

            // Receive 2 byte response...
            if (nGot != 2)
            {
                throw new ConnectionException("Bad response received from proxy server.");
            }

            if (response[1] == 0xFF)
            {    // No authentication method was accepted close the socket.
                s.Close();
                throw new ConnectionException("None of the authentication method was accepted by proxy server.");
            }

            byte[] rawBytes;
            //Username/Password Authentication protocol
            if (response[1] == 0x02)
            {
                nIndex            = 0;
                request[nIndex++] = 0x01; // Version 5.

                // add user name
                request[nIndex++] = (byte)userName.Length;
                rawBytes          = Encoding.UTF8.GetBytes(userName);
                rawBytes.CopyTo(request, nIndex);
                nIndex += (ushort)rawBytes.Length;

                // add password
                request[nIndex++] = (byte)password.Length;
                rawBytes          = Encoding.UTF8.GetBytes(password);
                rawBytes.CopyTo(request, nIndex);
                nIndex += (ushort)rawBytes.Length;

                // Send the Username/Password request
                Send(s, request, 0, nIndex);
                nGot = Receive(s, response, 0, response.Length);

                if (nGot != 2)
                {
                    throw new ConnectionException("Bad response received from proxy server.");
                }
                if (response[1] != 0x00)
                {
                    throw new ConnectionException("Bad Usernaem/Password.");
                }
            }
            //// This version only supports connect command.
            //// UDP and Bind are not supported.

            // Send connect request now...
            nIndex            = 0;
            request[nIndex++] = 0x05;    // version 5.
            request[nIndex++] = 0x01;    // command = connect.
            request[nIndex++] = 0x00;    // Reserve = must be 0x00

            if (destIP != null)
            {
                // Destination adress in an IP.
                switch (destIP.AddressFamily)
                {
                case AddressFamily.InterNetwork:
                    // Address is IPV4 format
                    request[nIndex++] = 0x01;
                    rawBytes          = destIP.GetAddressBytes();
                    rawBytes.CopyTo(request, nIndex);
                    nIndex += (ushort)rawBytes.Length;
                    break;

                case AddressFamily.InterNetworkV6:
                    // Address is IPV6 format
                    request[nIndex++] = 0x04;
                    rawBytes          = destIP.GetAddressBytes();
                    rawBytes.CopyTo(request, nIndex);
                    nIndex += (ushort)rawBytes.Length;
                    break;
                }
            }
            else
            {
                // Dest. address is domain name.
                request[nIndex++] = 0x03;                               // Address is full-qualified domain name.
                request[nIndex++] = Convert.ToByte(destAddress.Length); // length of address.
                rawBytes          = Encoding.UTF8.GetBytes(destAddress);
                rawBytes.CopyTo(request, nIndex);
                nIndex += (ushort)rawBytes.Length;
            }

            // using big-edian byte order
            byte[] portBytes = BitConverter.GetBytes(destPort);
            for (int i = portBytes.Length - 1; i >= 0; i--)
            {
                request[nIndex++] = portBytes[i];
            }

            // send connect request.
            Send(s, request, 0, nIndex);
            nGot = Receive(s, response, 0, response.Length);

            if (response[1] != 0x00)
            {
                throw new ConnectionException(errorMsgs[response[1]]);
            }
            // Success Connected...
            return(s);
        }
            private void OnNameResolved(NameResolutionResult dnsResult)
            {
                if (dnsResult.NetworkInterface == null)
                {
                    if (filestream != null)
                    {
                        filestream.Close();
                    }
                    ctx.Post(result => {
                        this.OnError(new ErrorEventArgs(new DownloadException("Network not available")));
                    }, null);
                    return;
                }

                HttpWebRequest request = (HttpWebRequest)WebRequest.CreateHttp(uri);

                request.Method = "GET";

                Logger.log("DownloadRequestHandler", "Downloading " + uri.AbsoluteUri + " asynchronously...");

                request.BeginGetResponse(async callbackResult => {
                    DownloadFile df = (DownloadFile)callbackResult.AsyncState;

                    try {
                        HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(callbackResult);
                        Logger.log("DownloadRequestHandler", "Status: " + (int)response.StatusCode + " " + response.StatusDescription);
                        if (response.Headers["Content-Length"] != null)
                        {
                            Logger.log("DownloadRequestHandler", "Content length: " + response.Headers["Content-Length"]);
                        }
                        else
                        {
                            Logger.log("DownloadRequestHandler", "Content length: unknown");
                        }

                        Stream responseStream      = response.GetResponseStream();
                        BinaryReader br            = new BinaryReader(responseStream);
                        int responseTotalBytesRead = 0;
                        byte[] responseBuffer      = br.ReadBytes(4096);

                        while (responseBuffer.Length > 0)
                        {
                            responseTotalBytesRead += responseBuffer.Length;
                            await filestream.WriteAsync(responseBuffer, 0, responseBuffer.Length);
                            responseBuffer = br.ReadBytes(4096);
                        }
                        filestream.Close();

                        Logger.log("DownloadRequestHandler", "Wrote " + responseTotalBytesRead + " bytes");

                        ctx.Post(result => {
                            df.OnComplete((DownloadFileEventArgs)result);
                        }, new DownloadFileEventArgs(filestream.Name, responseTotalBytesRead));
                    } catch (WebException ex) {
                        DownloadException de;
                        // check if we have an expired or self-signed cert
                        if (ex.Status == WebExceptionStatus.UnknownError)
                        {
                            if (ex.Response.Headers.Count == 0 && uri.Scheme == "https")
                            {
                                de = new DownloadException("Invalid SSL certificate, returning a 400 Bad Request");
                            }
                            else
                            {
                                de = new DownloadException("File not found, returning a 404");
                            }
                        }
                        else
                        {
                            de = new DownloadException("400 Bad Request: " + ex.Status.ToString());
                        }
                        if (filestream != null)
                        {
                            filestream.Close();
                        }
                        ctx.Post(result => {
                            df.OnError(new ErrorEventArgs(de));
                        }, null);
                        Logger.log("DownloadRequestHandler", de.Message);
                    }
                }, this);
            }
        private void OnNameResolved(NameResolutionResult result)
        {
            if (result.NetworkErrorCode == NetworkError.Success)
            {
                IPEndPoint[] endpoints = result.IPEndPoints;
                IPAddress address = endpoints[0].Address;

                int port = GetPortFromAddress(address);
                System.Diagnostics.Debug.WriteLine(port);
                string url = "http://sandstorm.case.edu:" + port;

                var client = new WebClient();
                client.DownloadStringCompleted += client_DownloadStringCompleted;
                client.DownloadStringAsync(new Uri(url + "/peerlist"));
            }
        }
Example #14
0
        /// <summary>
        /// Extends BeginInvoke so that when a state object is not needed, null does not need to be passed.
        /// <example>
        /// nameresolutioncallback.BeginInvoke(result, callback);
        /// </example>
        /// </summary>
        public static IAsyncResult BeginInvoke(this NameResolutionCallback nameresolutioncallback, NameResolutionResult result, AsyncCallback callback)
        {
            if (nameresolutioncallback == null)
            {
                throw new ArgumentNullException("nameresolutioncallback");
            }

            return(nameresolutioncallback.BeginInvoke(result, callback, null));
        }
        /// <summary>
        /// Callback for ResolveHostNameAsync
        /// </summary>
        /// <param name="result">The IP Address</param>
        private void OnNameResolved(NameResolutionResult result)
        {
            IPEndPoint[] endpoints = result.IPEndPoints;

            // If resolved, it will provide me with an IP address
            if (endpoints != null && endpoints.Length > 0)
            {
                var ipAddress = endpoints[0].Address;
                Debug.WriteLine("The IP address is " + ipAddress.ToString());
                resolvedHost = ipAddress;
            }
            stopWaitHandle.Set();
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="NetInfo"></param>
        void NetResolutionCallback(NameResolutionResult NetResInfo)
        {
            if (NetResInfo.NetworkErrorCode == NetworkError.Success)
            {
                this.IsODataReachable = true;
            }

        }
        /// <summary>
        /// Extends BeginInvoke so that when a state object is not needed, null does not need to be passed.
        /// <example>
        /// nameresolutioncallback.BeginInvoke(result, callback);
        /// </example>
        /// </summary>
        public static IAsyncResult BeginInvoke(this NameResolutionCallback nameresolutioncallback, NameResolutionResult result, AsyncCallback callback)
        {
            if(nameresolutioncallback == null) throw new ArgumentNullException("nameresolutioncallback");

            return nameresolutioncallback.BeginInvoke(result, callback, null);
        }