public static IObservable <NameResolutionResult> ResolveHostName(DnsEndPoint endPoint, NetworkInterfaceInfo networkInterface) { Contract.Requires(endPoint != null); Contract.Requires(networkInterface != null); Contract.Ensures(Contract.Result <IObservable <NameResolutionResult> >() != null); var subject = new AsyncSubject <NameResolutionResult>(); try { DeviceNetworkInformation.ResolveHostNameAsync( endPoint, networkInterface, result => { var s = (AsyncSubject <NameResolutionResult>)result.AsyncState; s.OnNext(result); s.OnCompleted(); }, subject); } catch (Exception ex) { subject.OnError(ex); } return(subject.AsObservable()); }
public override Task <bool> IsHostReachable(string host) { var tcs = new TaskCompletionSource <bool>(); DeviceNetworkInformation.ResolveHostNameAsync(new DnsEndPoint(host, 80), x => tcs.SetResult(x.HostName != null), null); return(tcs.Task); }
public void getConnectionInfo(string empty) { // Use the GetIsNetworkAvailable method to quickly determine if we have a connection or not // Otherwise, resolving a DNS name with no connection takes a while. if (System.Net.NetworkInformation.NetworkInterface.GetIsNetworkAvailable()) { // We have to try to resolve a host name to get the specific subtype of network available. // Kind of a shitty API here MSFT DeviceNetworkInformation.ResolveHostNameAsync( new DnsEndPoint("microsoft.com", 80), new NameResolutionCallback(nrr => { if (nrr.NetworkErrorCode == NetworkError.Success) { updateConnectionType(checkConnectionType(nrr.NetworkInterface.InterfaceSubtype)); } else { updateConnectionType(NONE); } } ), null ); } else { updateConnectionType(NONE); } }
/// <summary> /// Tests if a host name is pingable /// </summary> /// <param name="host">The host name can either be a machine name, such as "java.sun.com", or a textual representation of its IP address (127.0.0.1)</param> /// <param name="msTimeout">Timeout in milliseconds</param> /// <returns></returns> public override async Task <bool> IsReachable(string host, int msTimeout = 5000) { if (string.IsNullOrEmpty(host)) { throw new ArgumentNullException("host"); } if (!IsConnected) { return(false); } return(await Task.Run(() => { var manualResetEvent = new ManualResetEvent(false); var reachable = false; DeviceNetworkInformation.ResolveHostNameAsync(new DnsEndPoint(host, 80), result => { reachable = result.NetworkInterface != null; manualResetEvent.Set(); }, null); manualResetEvent.WaitOne(TimeSpan.FromMilliseconds(msTimeout)); return reachable; })); }
/// <summary> /// Method to check internet connection to the host /// </summary> /// <returns></returns> public static bool CheckNetwork() { var manualResetEvent = new ManualResetEvent(false); bool internetConnectionAvailable = true; DeviceNetworkInformation.ResolveHostNameAsync(new DnsEndPoint("smartfiction.ru", 80), networkInfo => { if (networkInfo.NetworkInterface == null) { internetConnectionAvailable = false; } manualResetEvent.Set(); }, null); manualResetEvent.WaitOne(TimeSpan.FromMilliseconds(50)); if (!internetConnectionAvailable) { System.Windows.Deployment.Current.Dispatcher.BeginInvoke(() => { MessageBox.Show( "Так уж вышло, что для некоторых действий требуется интернет! В данный момент программа не может соединиться с smartfiction.ru", "Warning", MessageBoxButton.OK); //one can use here new Game().Exit() //throw new Exception( // "ExitApplicationException"); }); return(false); } return(true); }
public MainPage() { this.InitializeComponent(); this._feContainer = this.LayoutRoot; if (!DeviceNetworkInformation.get_IsNetworkAvailable()) { MessageBox.Show("Vui lòng kết nối 3g hoặc wifi"); Application.get_Current().Terminate(); } else { this.LoadQc(); } this._lsSaveFav = tiviViet.App.ListFavorite; this.FeedbackOverlay.VisibilityChanged += new EventHandler(this, tiviViet.MainPage.FeedbackOverlay_VisibilityChanged); if (!IsolatedStorageSettings.get_ApplicationSettings().Contains("Zipcodes")) { this.CreateTiles(); } if (!tiviViet.App.sttRemove) { this.ShowVideo(); this.btnRemove.set_Visibility(0); } Deployment.get_Current().get_Dispatcher().BeginInvoke(new Action(this, () => { this.LoadData(); GetData.CheckAppVersion(); })); }
public static Task <bool> check_internet_connection_hard() { //Thread.Sleep(10000);//في المين ثريد if (DeviceNetworkInformation.IsNetworkAvailable == false) { return(Task.FromResult(false)); } return(Task.Run(() => { //Thread.Sleep(3000);//في الثريد var manualResetEvent = new ManualResetEvent(false); var reachable = false; DeviceNetworkInformation.ResolveHostNameAsync(new DnsEndPoint("www.google.com", 80), result => { //Thread.Sleep(10000);//في الثريد reachable = result.NetworkInterface != null; manualResetEvent.Set(); }, null); manualResetEvent.WaitOne(TimeSpan.FromMilliseconds(10000)); //Thread.Sleep(10000); //في الثريد return reachable; })); }
private void ConnectButton_Click(object sender, EventArgs e) { string server = "sandstorm.case.edu"; DnsEndPoint endpoint = new DnsEndPoint(server, 0); DeviceNetworkInformation.ResolveHostNameAsync(endpoint, OnNameResolved, null); }
public Task <bool> IsReachable(string host, TimeSpan timeout) { return(Task <bool> .Run(() => { if (!DeviceNetworkInformation.IsNetworkAvailable) { return false; } AutoResetEvent e = new AutoResetEvent(false); bool isReachable = false; NameResolutionCallback d = delegate(NameResolutionResult result) { isReachable = result.NetworkErrorCode == NetworkError.Success; e.Set(); }; DeviceNetworkInformation.ResolveHostNameAsync(new System.Net.DnsEndPoint(host, 0), d, this); e.WaitOne(timeout); return isReachable; })); }
/// <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 btnHostResolve_Click(object sender, System.Windows.RoutedEventArgs e) { txIP.Text = ""; if (RscUtils.IsIpAddress(txHostName.Text)) { txIP.Text = "ERR: IP can not be resolved!"; } else { var endpoint = new DnsEndPoint(txHostName.Text, 0); DeviceNetworkInformation.ResolveHostNameAsync(endpoint, OnHostResolved, null); } }
/// <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); }
public async void send() { DeviceNetworkInformation.ResolveHostNameAsync(new DnsEndPoint(uri.Host, 0), OnNameResolved, null); }
public static void GetNetName() { DeviceNetworkInformation.ResolveHostNameAsync( new DnsEndPoint("www.microsoft.com", 80), new NameResolutionCallback(handle => { string Name = ""; string NetName = ""; NetworkInterfaceInfo info = handle.NetworkInterface; if (info != null) { Name = info.InterfaceName + " " + info.Description + " "; switch (info.InterfaceType) { case NetworkInterfaceType.Ethernet: NetName = "Ethernet"; break; case NetworkInterfaceType.MobileBroadbandCdma: case NetworkInterfaceType.MobileBroadbandGsm: switch (info.InterfaceSubtype) { case NetworkInterfaceSubType.Cellular_3G: //NetName = "Cellular_3G + 3G"; NetName = "3G"; break; case NetworkInterfaceSubType.Cellular_EVDO: //NetName = "Cellular_EVDO + 3G"; NetName = "3G"; break; case NetworkInterfaceSubType.Cellular_EVDV: //NetName = "Cellular_EVDV + 3G"; NetName = "3G"; break; case NetworkInterfaceSubType.Cellular_HSPA: NetName = "3G"; //NetName = "Cellular_HSPA + 3G"; break; case NetworkInterfaceSubType.Cellular_GPRS: //NetName = "Cellular_GPRS + 2G"; NetName = "2G"; break; case NetworkInterfaceSubType.Cellular_EDGE: NetName = "2G"; // NetName = "Cellular_EDGE + 2G"; break; case NetworkInterfaceSubType.Cellular_1XRTT: //NetName = "Cellular_1XRTT + 2G"; NetName = "2G"; break; default: NetName = "None"; break; } break; case NetworkInterfaceType.Wireless80211: NetName = "WiFi"; break; default: NetName = "None"; break; } } else { NetName = "None"; } CommonData.NetworkStatus = NetName; string tip = ""; if (NetName == "None") { tip = AppResources.NoneNetwork; } else { tip = AppResources.ShowNetwork.Replace("#name#", NetName); } if (NetName != "WiFi") { App.DownVideoModel.StopGetVideoData(); } else { App.DownVideoModel.CheckLocalData(); } ShowToast(tip); }), null); }
public void DnsLookup(string hostname, int port) { var endpoint = new DnsEndPoint(hostname, port, System.Net.Sockets.AddressFamily.InterNetwork); DeviceNetworkInformation.ResolveHostNameAsync(endpoint, OnNameResolved, null); }
private void OnOK() { bool bGoBack = true; if (!DeviceNetworkInformation.IsNetworkAvailable) { ConnectionSettingsTask connectionSettingsTask = new ConnectionSettingsTask(); connectionSettingsTask.ConnectionSettingsType = ConnectionSettingsType.WiFi; connectionSettingsTask.Show(); return; } if (m_AppInput != null) { string strRes = txSvrIP.Text; //NoEmpty... if (m_AppInput.GetFlag(1).Length > 0) { strRes = strRes.Trim(); if (strRes.Length == 0) { MessageBox.Show("Value must not be empty!"); return; } } /* * //FileName... * if( m_AppInput.GetFlag(1).Length > 0 ) * { * strRes = strRes.Trim(); * * string strChk = "\\/:*?\"<>|"; * foreach( char cChk in strChk ) * { * if( strRes.IndexOf( cChk ) >= 0 ) * { * MessageBox.Show("Value must not contain characters of '" + strChk + "'!"); * return; * } * } * } */ bGoBack = false; if (RscUtils.IsIpAddress(strRes)) { /* * MessageBox.Show("IP Address is not allowed here!"); * return; */ DoOk(); } else { prsBar.Visibility = Rsc.Visible; var endpoint = new DnsEndPoint(strRes, 0); DeviceNetworkInformation.ResolveHostNameAsync(endpoint, OnHostResolved, null); } } if (bGoBack) { this.NavigationService.GoBack(); } }
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); }
/// <summary> /// Gets the MEGA DNS servers IP addresses. /// </summary> /// <param name="refresh">Indicates if should refresh the previously stored addresses.</param> /// <returns>String with the MEGA DNS servers IP addresses separated by commas.</returns> public static string GetMegaDnsServers(bool refresh = true) { if (!refresh && !string.IsNullOrWhiteSpace(MegaDnsServers)) { return(MegaDnsServers); } try { if (!IsNetworkAvailable()) { return(null); } LogService.Log(MLogLevel.LOG_LEVEL_INFO, "Getting MEGA DNS servers..."); var endpoint = new DnsEndPoint("ns.mega.co.nz", 0); var autoResetEvent = new AutoResetEvent(false); DeviceNetworkInformation.ResolveHostNameAsync(endpoint, (NameResolutionResult result) => { string dnsServers = string.Empty; try { if (result.IPEndPoints != null) { IPEndPoint[] endpoints = result.IPEndPoints; foreach (IPEndPoint address in endpoints) { if (dnsServers.Length > 0) { dnsServers = string.Concat(dnsServers, ","); } dnsServers = string.Concat(dnsServers, address.Address.ToString()); } } if (string.IsNullOrWhiteSpace(dnsServers)) { LogService.Log(MLogLevel.LOG_LEVEL_WARNING, "No MEGA DNS servers."); autoResetEvent.Set(); return; } LogService.Log(MLogLevel.LOG_LEVEL_INFO, "MEGA DNS servers: " + dnsServers); MegaDnsServers = dnsServers; } catch (Exception e) { LogService.Log(MLogLevel.LOG_LEVEL_ERROR, "Error getting MEGA DNS servers.", e); } finally { autoResetEvent.Set(); } }, null); autoResetEvent.WaitOne(); return(MegaDnsServers); } catch (Exception e) { LogService.Log(MLogLevel.LOG_LEVEL_ERROR, "Error getting MEGA DNS servers.", e); return(null); } }
public void DnsLookupAsync(string hostname) { var endpoint = new DnsEndPoint(hostname, 0); DeviceNetworkInformation.ResolveHostNameAsync(endpoint, OnNameResolved, null); }