public bool IsResolvable(string host) { if (String.IsNullOrEmpty(host)) { return(false); } int millisecond_time_out = 1000; ResolveState ioContext = new ResolveState(host); var result = Dns.BeginGetHostEntry(ioContext.HostName, null, null); var success = result.AsyncWaitHandle.WaitOne(TimeSpan.FromMilliseconds(millisecond_time_out), true); if (!success) { ioContext.Result = Resolvetype.Timeout; } else { try { var ipList = Dns.EndGetHostEntry(result); if (ipList == null || ipList.AddressList == null || ipList.AddressList.Length == 0) { ioContext.Result = Resolvetype.InvalidHost; } else { ioContext.Result = Resolvetype.Completed; } } catch { ioContext.Result = Resolvetype.InvalidHost; } } return(ioContext.Result == Resolvetype.Completed); }
[Test] // BeginGetHostEntry (String, AsyncCallback, Object) public void BeginGetHostEntry2_HostNameOrAddress_UnspecifiedAddress() { // IPv4 try { Dns.BeginGetHostEntry( "0.0.0.0", new AsyncCallback(GetHostEntryCallback), null); Assert.Fail("#1"); } catch (ArgumentException ex) { // IPv4 address 0.0.0.0 and IPv6 address ::0 are // unspecified addresses that cannot be used as // a target address Assert.AreEqual(typeof(ArgumentException), ex.GetType(), "#2"); Assert.IsNull(ex.InnerException, "#3"); Assert.IsNotNull(ex.Message, "#4"); Assert.AreEqual("hostNameOrAddress", ex.ParamName, "#5"); } // IPv6 try { Dns.BeginGetHostEntry( "::0", new AsyncCallback(GetHostEntryCallback), null); Assert.Fail("#1"); } catch (ArgumentException ex) { // IPv4 address 0.0.0.0 and IPv6 address ::0 are // unspecified addresses that cannot be used as // a target address Assert.AreEqual(typeof(ArgumentException), ex.GetType(), "#2"); Assert.IsNull(ex.InnerException, "#3"); Assert.IsNotNull(ex.Message, "#4"); Assert.AreEqual("hostNameOrAddress", ex.ParamName, "#5"); } }
public static void EventSource_ResolveInvalidHostName_LogsStartFailureStop() { RemoteExecutor.Invoke(async() => { const string InvalidHostName = "invalid...example.com"; using var listener = new TestEventListener("System.Net.NameResolution", EventLevel.Informational); var events = new ConcurrentQueue <EventWrittenEventArgs>(); await listener.RunWithCallbackAsync(events.Enqueue, async() => { await Assert.ThrowsAnyAsync <SocketException>(async() => await Dns.GetHostEntryAsync(InvalidHostName)); await Assert.ThrowsAnyAsync <SocketException>(async() => await Dns.GetHostAddressesAsync(InvalidHostName)); Assert.ThrowsAny <SocketException>(() => Dns.GetHostEntry(InvalidHostName)); Assert.ThrowsAny <SocketException>(() => Dns.GetHostAddresses(InvalidHostName)); Assert.ThrowsAny <SocketException>(() => Dns.EndGetHostEntry(Dns.BeginGetHostEntry(InvalidHostName, null, null))); Assert.ThrowsAny <SocketException>(() => Dns.EndGetHostAddresses(Dns.BeginGetHostAddresses(InvalidHostName, null, null))); }); Assert.DoesNotContain(events, e => e.EventId == 0); // errors from the EventSource itself Assert.True(events.Count >= 3 * 6); EventWrittenEventArgs[] starts = events.Where(e => e.EventName == "ResolutionStart").ToArray(); Assert.Equal(6, starts.Length); Assert.All(starts, s => Assert.Equal(InvalidHostName, Assert.Single(s.Payload).ToString())); EventWrittenEventArgs[] failures = events.Where(e => e.EventName == "ResolutionFailed").ToArray(); Assert.Equal(6, failures.Length); EventWrittenEventArgs[] stops = events.Where(e => e.EventName == "ResolutionStop").ToArray(); Assert.Equal(6, stops.Length); }).Dispose(); }
internal static void CheckConnection() { //We are already connected. if ((connection != null && connection.ConnectionAlive()) || DateTime.UtcNow < punishmentReconnectTime || isConnecting) { return; } IPHostEntry hostEntry = null; Dns.BeginGetHostEntry(Config.DNS_HOST_NAME == "localhost" ? string.Empty : Config.DNS_HOST_NAME, (callback) => { isConnecting = true; hostEntry = Dns.EndGetHostEntry(callback); bool connected = false; for (ushort i = 0; i < hostEntry.AddressList.Length; i++) { for (byte j = 0; j < Config.PORT_NUMBERS.Length; j++) { try { connection = TCPConnection.GetConnection(new ConnectionInfo(new IPEndPoint(hostEntry.AddressList[i], Config.PORT_NUMBERS[j]))); connected = true; //We use this to exit the outer loop OnConnected(); break; } catch { } } if (connected) { break; } } isConnecting = false; }, null); }
/// <summary> /// 使用End方法名阻塞线程 /// </summary> public static void BlockUntilOperationCompletes(IPAddress ip) { IAsyncResult result = Dns.BeginGetHostEntry(ip, null, null); Console.WriteLine("APM End Thread id : {0}, processing request for information...", Thread.CurrentThread.ManagedThreadId); try { //调用End方法阻塞线程 IPHostEntry host = Dns.EndGetHostEntry(result); string[] aliases = host.Aliases; IPAddress[] addresses = host.AddressList; if (aliases.Length > 0) { Console.WriteLine("APM End Thread id : {0}, Aliases", Thread.CurrentThread.ManagedThreadId); for (int i = 0; i < aliases.Length; i++) { Console.WriteLine("APM End Thread id : {0}, {1}", Thread.CurrentThread.ManagedThreadId, aliases[i]); } } if (addresses.Length > 0) { Console.WriteLine("APM End Thread id : {0}, address", Thread.CurrentThread.ManagedThreadId); for (int i = 0; i < addresses.Length; i++) { Console.WriteLine("APM End Thread id : {0}, {1}", Thread.CurrentThread.ManagedThreadId, addresses[i]); } } } catch (SocketException e) { Console.WriteLine("APM End Thread id : {0}, Exception occurred while processing the request: {1}", Thread.CurrentThread.ManagedThreadId, e.Message); } }
public static int Main(string[] args) { AsyncCallback cback = new AsyncCallback(ResolveCallback); IAsyncResult res = Dns.BeginGetHostEntry("localhost", cback, null); System.Threading.Thread.Sleep(2000); /* * seems to be broken * while (!res.IsCompleted) { * System.Threading.Thread.Sleep(20); * }; * IPHostEntry ip = Dns.EndGetHostEntry (res); * Console.WriteLine (ip);*/ if (frame_count < 1) { return(1); } // A test for #444383 AppDomain.CreateDomain("1").CreateInstance(typeof(Class1).Assembly.GetName().Name, "Class1"); return(0); }
public static void EventSource_GetHostEntryForIP_LogsStartStop() { RemoteExecutor.Invoke(async() => { const string ValidIPAddress = "8.8.4.4"; using var listener = new TestEventListener("System.Net.NameResolution", EventLevel.Informational); var events = new ConcurrentQueue <EventWrittenEventArgs>(); await listener.RunWithCallbackAsync(events.Enqueue, async() => { IPAddress ipAddress = IPAddress.Parse(ValidIPAddress); await Dns.GetHostEntryAsync(ValidIPAddress); await Dns.GetHostEntryAsync(ipAddress); Dns.GetHostEntry(ValidIPAddress); Dns.GetHostEntry(ipAddress); Dns.EndGetHostEntry(Dns.BeginGetHostEntry(ValidIPAddress, null, null)); Dns.EndGetHostEntry(Dns.BeginGetHostEntry(ipAddress, null, null)); }); Assert.DoesNotContain(events, e => e.EventId == 0); // errors from the EventSource itself // Each GetHostEntry over an IP will yield 2 resolutions EventWrittenEventArgs[] starts = events.Where(e => e.EventName == "ResolutionStart").ToArray(); Assert.Equal(12, starts.Length); Assert.Equal(6, starts.Count(s => Assert.Single(s.Payload).ToString() == ValidIPAddress)); EventWrittenEventArgs[] stops = events.Where(e => e.EventName == "ResolutionStop").ToArray(); Assert.Equal(12, stops.Length); Assert.DoesNotContain(events, e => e.EventName == "ResolutionFailed"); }).Dispose(); }
public void AsyncGetHostEntry(string host, Action <IPHostEntry> resultAction) { Logger.DEBUG(host); try { IPAddress iPAddress = null; if (IPAddress.TryParse(host, ref iPAddress)) { IPHostEntry iPHostEntry = new IPHostEntry(); iPHostEntry.set_AddressList(new IPAddress[] { iPAddress }); resultAction.Invoke(iPHostEntry); } else if (this.dnsCache.ContainsKey(host)) { IPHostEntry iPHostEntry2 = this.dnsCache.get_Item(host); resultAction.Invoke(iPHostEntry2); } else { Action <IAsyncResult> action = delegate(IAsyncResult ar) { try { string text = (string)ar.get_AsyncState(); Logger.DEBUG(text + " end"); IPHostEntry entry = Dns.EndGetHostEntry(ar); Logger.DEBUG(text + " end, entry.AddressList.Length=" + entry.get_AddressList().Length.ToString()); Action <int, Dictionary <string, object> > action2 = delegate(int status, Dictionary <string, object> content) { string text2 = content.get_Item("host") as string; IPHostEntry iPHostEntry3 = content.get_Item("entry") as IPHostEntry; Action <IPHostEntry> action3 = content.get_Item("resultAction") as Action <IPHostEntry>; this.dnsCache.set_Item(text2, entry); action3.Invoke(entry); }; Message message = new Message(); message.status = 0; message.content.set_Item("host", text); message.content.set_Item("entry", entry); message.content.set_Item("resultAction", resultAction); message.action = action2; this.EnqueueDrive(message); } catch (Exception ex2) { Logger.ERROR(ex2.get_Message() + ":" + ex2.get_StackTrace()); } }; Logger.DEBUG(host + " begin"); Dns.BeginGetHostEntry(host, new AsyncCallback(action.Invoke), host); } } catch (Exception ex) { resultAction.Invoke(null); Logger.ERROR(ex.get_Message() + ":" + ex.get_StackTrace()); } }
private static void Main(string[] args) { if (string.Join(" ", args).Contains("logo")) { ConsoleUtil.ShowAppHeader(Assembly.GetExecutingAssembly()); } var appInfo = new ApplicationInfo { AssemblyInfo = Assembly.GetExecutingAssembly(), CommandlineArgumentInfos = GetArguments(), ParameterDelimiter = '=', ParameterPraefix = '-' }; if (!AppUtil.AreCommandArgumentsValid(args, appInfo)) { ConsoleUtil.PrintArgumentError(appInfo, string.Join("\n", AppUtil.CheckCommandArguments(args, appInfo).AsEnumerable())); } else { var list = AppUtil.MapCommandArguments(args, appInfo); var result = 0; string givenValue; var ports = new List <int>(); string portValue; int timeout; int repeats; bool autoStop; bool useUdp; bool detailledState; try { givenValue = list.First(a => a.Abbreviation == "a").GivenValue; portValue = list.First(a => a.Abbreviation == "p").GivenValue; if (portValue.Contains(",")) { portValue.Split(',').ToList().ForEach(p => ports.Add(int.Parse(p.Trim()))); } else { if (portValue.Contains('-')) { var portsRanged = portValue.Split('-'); var from = int.Parse(portsRanged[0]); var to = int.Parse(portsRanged[1]); for (var p = from; p <= to; p++) { ports.Add(p); } } else { ports.Add(int.Parse(portValue)); } } timeout = int.Parse(list.First(a => a.Abbreviation == "tim").ResolvedValue); repeats = int.Parse(list.First(a => a.Abbreviation == "r").ResolvedValue); autoStop = list.SingleOrDefault(a => a.Abbreviation == "as") != null; useUdp = list.SingleOrDefault(a => a.Abbreviation == "u") != null; detailledState = list.SingleOrDefault(a => a.Abbreviation == "d") != null; if (list.SingleOrDefault(a => a.Abbreviation == "t") != null) { repeats = int.MaxValue; } var commandlineArgumentInfo = list.SingleOrDefault(a => a.Abbreviation == "w"); if (commandlineArgumentInfo != null) { int.TryParse(commandlineArgumentInfo.ResolvedValue, out result); } } catch (Exception ex) { ConsoleUtil.WriteLine($"Error during parsing input parameters: {ex.Message}", ConsoleColor.Red); return; } if (string.IsNullOrEmpty(givenValue) || ports.Any(p => p <= 0)) { return; } Console.WriteLine( "Starting pinging host {0} on {3} port(s) {1} {2} times:", givenValue, portValue, repeats == int.MaxValue ? "infinite" : repeats.ToString(CultureInfo.InvariantCulture), useUdp ? "UDP" : "TCP"); var reachablePorts = 0; var closedPorts = 0; var hostIp = "-"; if (list.FirstOrDefault(a => a.Abbreviation == "res") != null) { // we have to perform address resolution Dns.BeginGetHostEntry( givenValue, ar => { IPHostEntry local0 = null; try { local0 = Dns.EndGetHostEntry(ar); } catch { // empty catch } if (local0 == null || !local0.AddressList.Any()) { return; } hostIp = local0.AddressList[0].ToString(); }, null); } // start the process var currentPack = 0; for (var i = 0; i < repeats; ++i) { var portOpen = true; ports.ForEach( port => { try { portOpen &= NetworkUtil.IsPortOpened(givenValue, port, timeout, useUdp); reachablePorts += portOpen ? 1 : 0; closedPorts += portOpen ? 0 : 1; var printResult = portOpen ? "OPEN" : "CLOSED"; if (detailledState && !portOpen) { printResult += $" ({NetworkUtil.LastCheckResult.ToString()})"; } Console.Write("#{0,4} -> Pinging host {1} (IP:{2}) on {5} port {3} with timeout {4}: ", ++currentPack, givenValue, hostIp, port, timeout, useUdp ? "UDP" : "TCP"); ConsoleUtil.WriteLine(printResult, portOpen ? ConsoleColor.DarkGreen : ConsoleColor.DarkRed); } catch (Exception ex) { ConsoleUtil.WriteLine($"#{++currentPack,4} Error pinging host {givenValue}: {ex.Message}", ConsoleColor.Red); } }); if (!autoStop || !portOpen) { if (result > 0) { Thread.Sleep(result); } } else { break; } } Console.WriteLine("Finished pinging host {0} (IP:{1}). {2} pings sent ({3} OPEN, {4} CLOSED)", givenValue, hostIp, currentPack, reachablePorts, closedPorts); if (list.FirstOrDefault(a => a.Abbreviation == "elf") != null) { // return error level 1 if all pings where closed and 0 if any of them was open Environment.Exit(reachablePorts > 0 ? 0 : 1); } if (list.FirstOrDefault(a => a.Abbreviation == "elsc") != null) { // return the amount of opened pings as the error level Environment.Exit(reachablePorts); } } }
// Token: 0x0600074B RID: 1867 RVA: 0x0003AA62 File Offset: 0x00038C62 public ZConnector2(string host, int port) { this.m_host = host; this.m_port = port; Dns.BeginGetHostEntry(host, new AsyncCallback(this.OnHostLookupDone), null); }
/// <summary> /// Resolve a host IP address to a host name /// </summary> /// <remarks>This first makes a DNS query and uses the result if found. If not found it then tries a Microsoft DNS call which also searches the local hosts and makes a netbios query. /// If this returns an answer it is use. Otherwise the IP address is returned as the host name</remarks> private void ResolveIpAddressToHostName(object deviceIpEndPointObject) { IPEndPoint deviceIpEndPoint = null; try { deviceIpEndPoint = deviceIpEndPointObject as IPEndPoint; // Get the supplied device endpoint as an IPEndPoint // test whether the cast was successful if (deviceIpEndPoint is object) // The cast was successful so we can try to search for the host name { var dnsResponse = new DnsResponse(); // Create a new DnsResponse to hold and return the // Calculate the remaining time before this discovery needs to finish and only undertake DNS resolution if sufficient time remains var timeOutTime = TimeSpan.FromSeconds(discoveryTime).Subtract(DateTime.Now - discoveryStartTime).Subtract(TimeSpan.FromSeconds(0.2d)); if (timeOutTime.TotalSeconds > Constants.MINIMUM_TIME_REMAINING_TO_UNDERTAKE_DNS_RESOLUTION) // We have more than the configured time left so we will attempt a reverse DNS name resolution { LogMessage("ResolveIpAddressToHostName", $"Resolving IP address: {deviceIpEndPoint.Address}, Timeout: {timeOutTime}"); Dns.BeginGetHostEntry(deviceIpEndPoint.Address.ToString(), new AsyncCallback(GetHostEntryCallback), dnsResponse); // Wait here until the resolve completes and the callback calls .Set() bool dnsWasResolved = dnsResponse.CallComplete.WaitOne(timeOutTime); // Wait for the remaining discovery time // Execution continues here after either a DNS response is found or the request times out if (dnsWasResolved) // A response was received rather than timing out { LogMessage("ResolveIpAddressToHostName", $"{deviceIpEndPoint} has host name: {dnsResponse.HostName} IP address count: {dnsResponse.AddressList.Length} Alias count: {dnsResponse.Aliases.Length}"); foreach (IPAddress address in dnsResponse.AddressList) { LogMessage("ResolveIpAddressToHostName", $" Received {address.AddressFamily} address: {address}"); } foreach (string hostAlias in dnsResponse.Aliases) { LogMessage("ResolveIpAddressToHostName", $" Received alias: {hostAlias}"); } if (dnsResponse.AddressList.Length > 0) // We got a reply that contains host addresses so there may be a valid host name { lock (deviceListLockObject) { if (!string.IsNullOrEmpty(dnsResponse.HostName)) { alpacaDeviceList[deviceIpEndPoint].HostName = dnsResponse.HostName; } } RaiseAnAlpacaDevicesChangedEvent(); // Device list was changed so set the changed flag } else { LogMessage("ResolveIpAddressToHostName", $"***** DNS responded with a name ({dnsResponse.HostName}) but this has no associated IP addresses and is probably a NETBIOS name *****"); } foreach (IPAddress address in dnsResponse.AddressList) { LogMessage("ResolveIpAddressToHostName", $"Address: {address}"); } foreach (string alias in dnsResponse.Aliases) { LogMessage("ResolveIpAddressToHostName", $"Alias: {alias}"); } } else // DNS did not respond in time { LogMessage("ResolveIpAddressToHostName", $"***** DNS did not respond within timeout - unable to resolve IP address to host name *****"); } } else // There was insufficient time to query DNS { LogMessage("ResolveIpAddressToHostName", $"***** Insufficient time remains ({timeOutTime.TotalSeconds} seconds) to conduct a DNS query, ignoring request *****"); } } else // The IPEndPoint cast was not successful so we cannot carry out a DNS name search because we don't have the device's IP address { LogMessage("ResolveIpAddressToHostName", $"DNS resolution could not be undertaken - It was not possible to cast the supplied IPEndPoint object to an IPEndPoint type: {deviceIpEndPoint}."); } } catch (TimeoutException) { LogMessage("ResolveIpAddressToHostName", $"Timed out trying to resolve the DNS name for {(deviceIpEndPoint is null ? "Unknown IP address" : deviceIpEndPoint.ToString()) }"); } catch (Exception ex) { // Something went wrong, so log the issue and sent a message to the user LogMessage("ResolveIpAddressToHostName", $"Exception: {ex}"); } }
static void Main(string[] args) { // Make sure the caller supplied a host name. if (args.Length == 0 || args[0].Length == 0) { // Print a message and exit. Console.WriteLine("You must specify the name of a host computer."); return; } // Start the asynchronous request for DNS information. IAsyncResult result = Dns.BeginGetHostEntry(args[0], null, null); Console.WriteLine("Processing request for information..."); // Wait until the operation completes. result.AsyncWaitHandle.WaitOne(); // The operation completed. Process the results. try { // Get the results. IPHostEntry host = Dns.EndGetHostEntry(result); string[] aliases = host.Aliases; IPAddress[] addresses = host.AddressList; if (aliases.Length > 0) { Console.WriteLine("Aliases"); for (int i = 0; i < aliases.Length; i++) { Console.WriteLine("{0}", aliases[i]); } } if (addresses.Length > 0) { Console.WriteLine("Addresses"); for (int i = 0; i < addresses.Length; i++) { Console.WriteLine("{0}", addresses[i].ToString()); } } } catch (SocketException e) { Console.WriteLine("Exception occurred while processing the request: {0}", e.Message); } Console.ReadLine(); // Linq LinqExample ex = new LinqExample(); //ex.LinqConsole(); student_a entity1 = new student_a(); #region 字段属性,抽象方法,虚方法 //entity1.Test(); // 普通方法 //entity1.Abstract_Test(); // 抽象方法 //entity1.Abstract_Test1(); // 抽象方法 //entity1.Virtual_Test();// 虚方法 //entity1.Virtual_Test1();// 重写虚方法 // entity1.Name = "北京欢迎你"; // Console.WriteLine(entity1.Name); //entity1.setAge(11); //Console.WriteLine(entity1.getAge().ToString()); #endregion #region 委托 //delegate_test dt = new delegate_test(); //dt.main(); #endregion #region 泛型 #region ArrayList //System.Collections.ArrayList list = new System.Collections.ArrayList(); //// Add an integer to the list. //list.Add(3); //// Add a string to the list. This will compile, but may cause an error later. //list.Add("It is raining in Redmond."); //int t = 0; //// This causes an InvalidCastException to be returned. //foreach (int x in list) //{ // t += x; //} //List<int> listtt = new List<int> {1,2,3,4,5 }; #endregion #region 参数委托约束 if (1 > 3) { var map = Test2.EnumNameValues <RainBow>(); foreach (var pair in map) { Console.WriteLine($"{pair.Key}:\t{pair.Value}"); } } #endregion #region 泛型接口 if (1 > 3) { //Person is the type argument. SortedList <Person> list = new SortedList <Person>(); //Create name and age values to initialize Person objects. string[] names = new string[] { "a", "b", "c" }; int[] ages = new int[] { 1, 2, 3 }; //Populate the list. for (int x = 0; x < 3; x++) { list.AddHead(new Person(names[x], ages[x])); } //Print out unsorted list. foreach (Person p in list) { System.Console.WriteLine(p.ToString()); } System.Console.WriteLine("Done with unsorted list"); //Sort the list. list.BubbleSort(); //Print out sorted list. foreach (Person p in list) { System.Console.WriteLine(p.ToString()); } System.Console.WriteLine("Done with sorted list"); } #endregion #endregion #region 元组 if (1 > 3) { var ToString = "This is some text"; var one = 1; var Item1 = 5; var projections = (ToString, one, Item1); // Accessing the first field: Console.WriteLine(projections.Item1); //Console.WriteLine(projections.ToStrings); // There is no semantic name 'ToString' // Accessing the second field: Console.WriteLine(projections.one); Console.WriteLine(projections.Item2); // Accessing the third field: Console.WriteLine(projections.Item3); // There is no semantic name 'Item`. var pt1 = (X : 3, Y : 0); var pt2 = (X : 3, Y : 4); var xCoords = (pt1.X, pt2.X); // There are no semantic names for the fields // of xCoords. // Accessing the first field: Console.WriteLine(xCoords.Item1); // Accessing the second field: Console.WriteLine(xCoords.Item2); } if (1 > 3) { // The 'arity' and 'shape' of all these tuples are compatible. // The only difference is the field names being used. var unnamed = (42, "The meaning of life"); var anonymous = (16, "a perfect square"); var named = (Answer : 42, Message : "The meaning of life"); var differentNamed = (SecretConstant : 42, Label : "The meaning of life 123456"); unnamed = named; // Console.WriteLine($"{unnamed.Item1}, {unnamed.Message}"); named = unnamed; // 'named' still has fields that can be referred to // as 'answer', and 'message': Console.WriteLine($"{named.Answer}, {named.Message}"); // unnamed to unnamed: anonymous = unnamed; // named tuples. named = differentNamed; // The field names are not assigned. 'named' still has // fields that can be referred to as 'answer' and 'message': Console.WriteLine($"{named.Answer}, {named.Message}"); (long, string)conversion = named; Console.WriteLine($"{conversion.Item1}, {conversion.Item2}"); } #endregion #region 运算符 if (1 > 3) { string[] arrNum = { "zero", "one", "two", "three", "four", "five", "six", "seven" }; var shortDig = arrNum.Where((a, index) => a.Length < index); foreach (var sd in shortDig) { Console.WriteLine(sd); } } #endregion #region 迭代器 if (1 > 3) { DaysOfTheWeek week = new DaysOfTheWeek(); foreach (string day in week) { Console.WriteLine(day + " _ "); } } #endregion Console.ReadLine(); }
static internal IAsyncResult BeginGetHostByName(string hostName, AsyncCallback cb, object state) { return(Dns.BeginGetHostEntry(hostName, cb, state)); }
public bool LookupHostName(IPAddress remoteAddress, object target, Action <object, string, NameSources> setter) { if (remoteAddress.Equals(IPAddress.Any) || remoteAddress.Equals(IPAddress.IPv6Any)) { return(true); } if (remoteAddress.Equals(IPAddress.Loopback) || remoteAddress.Equals(IPAddress.IPv6Loopback)) { return(true); } ReverseDnsEntry Entry = null; if (ReverseDnsCache.TryGetValue(remoteAddress, out Entry)) { if ((Entry.TimeStamp + (5 * 60 * 1000) >= MiscFunc.GetCurTick())) { if (Entry.HostName != null) { setter(target, Entry.HostName, NameSources.ReverseDNS); } return(true); } } if (Entry == null) { Entry = new ReverseDnsEntry(); ReverseDnsCache.Add(remoteAddress, Entry); } if (Entry.PendingJobs == null) { Entry.PendingJobs = new List <HostLookupJob>(); //AppLog.Debug("reverse looking up : {0}", remoteAddress.ToString()); // todo: use matibe api to save oin dns queries Dns.BeginGetHostEntry(remoteAddress, (x) => { // WARNING: this function is called from the worker thread //x.AsyncState IPHostEntry hostInfo = null; try { hostInfo = Dns.EndGetHostEntry(x); } catch { } App.engine?.RunInEngineThread(() => { // Note: this happens in the engine thread Entry.TimeStamp = MiscFunc.GetCurTick(); if (hostInfo != null) { Entry.HostName = hostInfo.HostName; } if (Entry.HostName != null) { foreach (var job in Entry.PendingJobs) { job.SetHostName(Entry.HostName, NameSources.ReverseDNS); } } Entry.PendingJobs = null; }); }, null); } Entry.PendingJobs.Add(new HostLookupJob() { target = new WeakReference(target), setter = setter }); return(false); }
private void CallbackOnNewPC(PC pc) { object[] objArray = new object[] { pc }; Invoke(new delegateOnNewPC(AddPc), objArray); Dns.BeginGetHostEntry(pc.ip.ToString(), new AsyncCallback(this.EndResolvCallBack), pc); }
protected void ProcessPendingClients() { PendingClient[] clients = null; lock (PendingClients) clients = PendingClients.ToArray(); while (clients.Length > 0) { foreach (PendingClient c in clients) { if (!c.DNSStarted) { var address = ((IPEndPoint)c.ClientConnection.Client.RemoteEndPoint).Address.ToString(); Logger.Log3("DNS Lookup started for " + address); Dns.BeginGetHostEntry(address, DNSLookupCompleted, c); c.DNSStarted = true; } else if (!c.DNSPassed) { if (c.HostEntry != null) { Logger.Log3("Ban check started for " + c.HostEntry.HostName); // lookup the host in the ban list bool ban = false; string reason = string.Empty; if (CheckHostBan != null) { ban = CheckHostBan(c, ref reason); } if (!ban) { c.DNSPassed = true; } else { c.HostEntry = null; DisconnectPendingClient(c); } } } if (!c.Active) { continue; } int available = c.ClientConnection.Available; if (c.ClientConnection.Available > 0) { if (!c.ProtcolPassed && c.ClientConnection.Available >= Protocol.BZFSHail.Length) { c.DataRecieved = true; byte[] buffer = new byte[Protocol.BZFSHail.Length]; int read = c.NetStream.Read(buffer, 0, buffer.Length); if (read != buffer.Length) { c.ProtcolPassed = false; DisconnectPendingClient(c); Logger.Log4("Disconnecting abnormal connection from " + c.ClientConnection.Client.RemoteEndPoint.ToString()); } else { if (Encoding.ASCII.GetString(buffer) == Protocol.BZFSHailString) { c.ProtcolPassed = true; c.NetStream.Write(Protocol.DefaultBZFSVersion, 0, Protocol.DefaultBZFSVersion.Length); c.NetStream.Flush(); c.VersionPassed = true; Logger.Log4("BZFS header from " + c.ClientConnection.Client.RemoteEndPoint.ToString()); } } } } if (c.Active) { if (c.DNSStarted && c.DNSPassed && c.DataRecieved && c.ProtcolPassed && c.VersionPassed) { RemovePendingClient(c); Logger.Log4("Accepted BZFS connection from " + c.ClientConnection.Client.RemoteEndPoint.ToString()); // send them off to the next step if (BZFSProtocolConnectionAccepted != null) { BZFSProtocolConnectionAccepted.Invoke(this, c); } } } } Thread.Sleep(100); lock (PendingClients) clients = PendingClients.ToArray(); } WorkerThread = null; }
public static void Main() { // Create the delegate that will process the results of the // asynchronous request. AsyncCallback callBack = new AsyncCallback(ProcessDnsInformation); string host; do { Console.Write(" Enter the name of a host computer or <enter> to finish: "); host = Console.ReadLine(); if (host.Length > 0) { // Increment the request counter in a thread safe manner. Interlocked.Increment(ref requestCounter); // Create and store the state object for this request. HostRequest request = new HostRequest(host); hostData.Add(request); // Start the asynchronous request for DNS information. Dns.BeginGetHostEntry(host, callBack, request); } } while (host.Length > 0); // The user has entered all of the host names for lookup. // Now wait until the threads complete. while (requestCounter > 0) { UpdateUserInterface(); } // Display the results. foreach (HostRequest r in hostData) { if (r.ExceptionObject != null) { Console.WriteLine("Request for host {0} returned the following error: {1}.", r.HostName, r.ExceptionObject.Message); } else { // Get the results. IPHostEntry h = r.HostEntry; string[] aliases = h.Aliases; IPAddress[] addresses = h.AddressList; if (aliases.Length > 0) { Console.WriteLine("Aliases for {0}", r.HostName); for (int j = 0; j < aliases.Length; j++) { Console.WriteLine("{0}", aliases[j]); } } if (addresses.Length > 0) { Console.WriteLine("Addresses for {0}", r.HostName); for (int k = 0; k < addresses.Length; k++) { Console.WriteLine("{0}", addresses[k].ToString()); } } } } }
/// <summary> /// Internal representation of the job logic. /// </summary> private async Task Run() { var runs = 0; var shouldRun = true; var overallWatch = new Stopwatch(); var portWatch = new Stopwatch(); overallWatch.Start(); while (!_tokenSource.IsCancellationRequested && shouldRun) { runs++; State = JobStateEnum.Running; JobDefinition.TargetPorts.ToList().ForEach( port => { try { var runResult = new JobSingleRunModel { Tcp = JobDefinition.Tcp, Udp = JobDefinition.Udp, Port = port }; portWatch.Restart(); runResult.PortReached = NetworkUtil.IsPortOpened(JobDefinition.TargetAddess, port, (int)JobDefinition.Timeout.TotalSeconds, JobDefinition.Udp); portWatch.Stop(); runResult.Duration = portWatch.Elapsed; if (JobDefinition.ResolveAddress) { // job should try to resolve ip address Dns.BeginGetHostEntry( JobDefinition.TargetAddess, ar => { IPHostEntry firstNetworkAddress = null; try { firstNetworkAddress = Dns.EndGetHostEntry(ar); } catch { // empty catch } if (firstNetworkAddress == null || !firstNetworkAddress.AddressList.Any()) { return; } runResult.ResolvedAddress = firstNetworkAddress.AddressList[0].ToString(); }, null); } DispatcherHelper.BeginInvoke(() => Result.Runs.Add(runResult)); ResultReceived?.Invoke(this, new JobResultEventArgs(runResult)); if (runResult.PortReached && JobDefinition.AutoStop) { // the port is reached and autostop is on shouldRun = false; return; } if (JobDefinition.MaxTries.HasValue && JobDefinition.MaxTries.Value <= runs) { // the maximum amount of tries is reached shouldRun = false; return; } if (JobDefinition.MaxRuntime.HasValue && JobDefinition.MaxRuntime.Value <= overallWatch.Elapsed) { // maximum runtime is reached shouldRun = false; return; } // inform callers that there is a new result // ReSharper disable once ExplicitCallerInfoArgument OnPropertyChanged(nameof(Result)); } catch (Exception ex) { // TODO } }); State = JobStateEnum.Waiting; await Task.Delay(JobDefinition.WaitTime, CancellationToken.None); } overallWatch.Stop(); }
/// <summary> /// Initializes the <see cref="LilaPing"/> class. /// </summary> static LilaPing() { Dns.BeginGetHostEntry("socket.lichess.org", OnInitComplete, null); }
public static void DNSConnect(string hostName, string PORT_NO) { Dns.BeginGetHostEntry(hostName, GetHostEntryCallback, PORT_NO); }
public void DnsBeginGetHostEntry_BadIpString_Throws() { IAsyncResult asyncObject = Dns.BeginGetHostEntry("0.0.1.1", null, null); Assert.ThrowsAny <SocketException>(() => Dns.EndGetHostEntry(asyncObject)); }
public static void Main() { // Create the delegate that will process the results of the // asynchronous request. AsyncCallback callBack = new AsyncCallback(ProcessDnsInformation); string host; do { Console.Write(" Enter the name of a host computer or <enter> to finish: "); host = Console.ReadLine(); if (host.Length > 0) { // Increment the request counter in a thread safe manner. Interlocked.Increment(ref requestCounter); // Start the asynchronous request for DNS information. Dns.BeginGetHostEntry(host, callBack, host); } } while (host.Length > 0); // The user has entered all of the host names for lookup. // Now wait until the threads complete. while (requestCounter > 0) { UpdateUserInterface(); } // Display the results. for (int i = 0; i < hostNames.Count; i++) { object data = hostData[i]; string message = data as string; // A SocketException was thrown. if (message != null) { Console.WriteLine("Request for {0} returned message: {1}", hostNames[i], message); continue; } // Get the results. IPHostEntry h = (IPHostEntry)data; string[] aliases = h.Aliases; IPAddress[] addresses = h.AddressList; if (aliases.Length > 0) { Console.WriteLine("Aliases for {0}", hostNames[i]); for (int j = 0; j < aliases.Length; j++) { Console.WriteLine("{0}", aliases[j]); } } if (addresses.Length > 0) { Console.WriteLine("Addresses for {0}", hostNames[i]); for (int k = 0; k < addresses.Length; k++) { Console.WriteLine("{0}", addresses[k].ToString()); } } } Console.ReadLine(); }
public void Start() { Dns.BeginGetHostEntry("www.google.com", new AsyncCallback(Stop), "Lookin up Google"); }
//Single thread private void handshakeReceiveCallback(IAsyncResult ar) { //this check is moved to except //try //{ // //already recycle // lock (this) // { // if (closed) // return; // } //} //catch (Exception) //{ // return; //} try { int bytesRead = connection.EndReceive(ar); if (bytesRead == 0) { throw new Exception("Error When handshakeReceiveCallback"); } //Console.WriteLine("bytesRead" + bytesRead.ToString() + " stage" + stage.ToString()); if (stage == 0) { //recv numbers of ivlen data byte[] iv = encryptor.Decrypt(this.connetionBuffer, bytesRead); //Decrypt sucessful //iv stage = 1; connection.BeginReceive(this.connetionBuffer, 0, 1, 0, new AsyncCallback(handshakeReceiveCallback), null); } else if (stage == 1) { byte[] buff = encryptor.Decrypt(this.connetionBuffer, bytesRead); //Decrypt sucessful //addrtype char addrtype = (char)buff[0]; if (addrtype == 1) { //type of ipv4 stage = 4; connection.BeginReceive(this.connetionBuffer, 0, 4, 0, new AsyncCallback(handshakeReceiveCallback), addrtype); } else if (addrtype == 3) { //type of url stage = 3; connection.BeginReceive(this.connetionBuffer, 0, 1, 0, new AsyncCallback(handshakeReceiveCallback), addrtype); } else if (addrtype == 4) { //type of ipv6 stage = 4; connection.BeginReceive(this.connetionBuffer, 0, 16, 0, new AsyncCallback(handshakeReceiveCallback), addrtype); } else { throw new Exception("Error Socket5 AddrType"); } } else if (stage == 3) { //addr len byte[] buff = encryptor.Decrypt(this.connetionBuffer, bytesRead); stage = 4; //recv addr connection.BeginReceive(this.connetionBuffer, 0, buff[0], 0, new AsyncCallback(handshakeReceiveCallback), ar.AsyncState); } else if (stage == 4) { //addr byte[] buff = encryptor.Decrypt(this.connetionBuffer, bytesRead); if (1 == (char)ar.AsyncState) { //ipv4 destAddr = string.Format("{0:D}.{1:D}.{2:D}.{3:D}", buff[0], buff[1], buff[2], buff[3]); } else if (3 == (char)ar.AsyncState) { //ipv6 url destAddr = ASCIIEncoding.Default.GetString(buff); } else { //url destAddr = string.Format("[{0:x2}{1:x2}:{2:x2}{3:x2}:{4:x2}{5:x2}:{6:x2}{7:x2}:{8:x2}{9:x2}:{10:x2}{11:x2}:{12:x2}{13:x2}:{14:x2}{15:x2}]" , buff[0], buff[1], buff[2], buff[3], buff[4], buff[5], buff[6], buff[7], buff[8], buff[9], buff[10], buff[11], buff[12], buff[13], buff[14], buff[15]); } stage = 5; //recv port connection.BeginReceive(this.connetionBuffer, 0, 2, 0, new AsyncCallback(handshakeReceiveCallback), null); } else if (stage == 5) { //port byte[] buff = encryptor.Decrypt(this.connetionBuffer, bytesRead); int port = (int)(buff[0] << 8) + (int)buff[1]; stage = 6; //handshake completed lock (timeOutTimer) { this.timeOutTimer.Dispose(); timeOutTimer = null; } //Begin to connect remote IPAddress ipAddress; bool parsed = IPAddress.TryParse(destAddr, out ipAddress); if (!parsed) { IPAddress cache_ipAddress = DNSCache.GetInstence().Get(destAddr); if (cache_ipAddress == null) { DNSCbContext ct = new DNSCbContext(destAddr, port); Dns.BeginGetHostEntry(destAddr, new AsyncCallback(GetHostEntryCallback), ct); return; } ipAddress = cache_ipAddress; } IPEndPoint remoteEP = new IPEndPoint(ipAddress, port); remote = new Socket(ipAddress.AddressFamily, SocketType.Stream, ProtocolType.Tcp); remote.BeginConnect(remoteEP, new AsyncCallback(remoteConnectCallback), null); } } catch (Exception e) { try { //handshake time out lock (timeOutTimer) { if (timeOutTimer != null) { this.timeOutTimer.Dispose(); } timeOutTimer = null; } Console.WriteLine(e.ToString()); this.Close(); } catch (Exception) { //already recycle } } }
private void OnStateChanged() { if (this.State == IrcSessionState.Connected && _findExternalAddress) { this.AddHandler(new IrcCodeHandler((e) => { e.Handled = true; if (e.Message.Parameters.Count < 2) { return(true); } var parts = e.Message.Parameters[1].Split('@'); if (parts.Length > 0) { IPAddress external; if (!IPAddress.TryParse(parts[1], out external)) { Dns.BeginGetHostEntry(parts[1], (ar) => { try { var host = Dns.EndGetHostEntry(ar); if (host.AddressList.Length > 0) { this.ExternalAddress = host.AddressList[0]; } } catch { } }, null); } else { this.ExternalAddress = external; } } return(true); }, IrcCode.RPL_USERHOST)); this.UserHost(this.Nickname); } this.RaiseEvent(this.StateChanged, EventArgs.Empty); if (this.State == IrcSessionState.Disconnected && this.AutoReconnect) { if (_reconnectTimer != null) { _reconnectTimer.Dispose(); } _reconnectTimer = new Timer(new TimerCallback((obj) => { if (_syncContext != null) { _syncContext.Post((o) => ((Action)o)(), (Action)this.OnReconnect); } else { this.OnReconnect(); } }), null, ReconnectWaitTime, System.Threading.Timeout.Infinite); } }
public static void Main() { // 針對非同步請求,產生委派方法,用於處理非同步工作執行完成後的結果 AsyncCallback callBack = new AsyncCallback(ProcessDnsInformation); string host; // 在這個迴圈內,我們可以輸入多個 URL,程式會立即啟動非同步工作取得該 URL 的內容 do { Console.Write(" 請輸入主機名稱,或直接按下 <enter> 按鈕表示完成所有輸入作業: "); host = Console.ReadLine(); if (host.Length > 0) { // 使用安全執行緒技巧,增加執行緒要使用的共用變數 [requestCounter] 的值,確保不會因為競賽,導致該變數的內容走味 //*********************************** // 遞增特定變數並將結果儲存起來,成為不可部分完成的作業。 // 在進行多執行緒存取分享資源的時候,尤其要特別注意 //*********************************** Interlocked.Increment(ref requestCounter); Console.WriteLine("正在取得與處理DNS的資訊..."); // 呼叫 BeginXXX 啟動非同步工作 Dns.BeginGetHostEntry(host, callBack, host); } } while (host.Length > 0); //*********************************** // 每次非同步作業完成後, requestCounter的就會減少一,由此判斷所有的非同步作業是否都已經完成 // 這樣的迴圈,也會造成系統資訊濫用 //*********************************** // 該迴圈的用意,僅是當所有非同步工作都處理完成之後,才會繼續執行該迴圈後的程式碼, // 也就是列出所有非同步執行結果的內容 // 即 // 若有任何一個非同步工作尚未完成的話,程式會一直在該迴圈內跑 while (requestCounter > 0) { UpdateUserInterface(); } // 若程式已經可以執行到這裡,那就表示所有非同步工作已經完成了 for (int i = 0; i < hostNames.Count; i++) { object data = hostData[i]; string message = data as string; // 一個 SocketException 已經產生了 if (message != null) { Console.WriteLine("{0} 請求的傳回訊息: {1}", hostNames[i], message); continue; } IPHostEntry h = (IPHostEntry)data; string[] aliases = h.Aliases; IPAddress[] addresses = h.AddressList; if (aliases.Length > 0) { Console.WriteLine("別名 {0}", hostNames[i]); for (int j = 0; j < aliases.Length; j++) { Console.WriteLine("{0}", aliases[j]); } } if (addresses.Length > 0) { Console.WriteLine("位址 {0}", hostNames[i]); for (int k = 0; k < addresses.Length; k++) { Console.WriteLine("{0}", addresses[k].ToString()); } } } Console.WriteLine("Press any key for continuing..."); Console.ReadKey(); }
/// <summary> /// Get IPv4 address from notation (xxx.xxx.xxx.xxx) or hostname (asynchronous version) /// </summary> public static void ResolveAsync(string ipOrHost, ResolveAddressCallback callback) { if (string.IsNullOrEmpty(ipOrHost)) { throw new ArgumentException("Supplied string must not be empty", "ipOrHost"); } ipOrHost = ipOrHost.Trim(); NetAddress ipAddress = null; if (NetAddress.TryParse(ipOrHost, out ipAddress)) { if (ipAddress.AddressFamily == AddressFamily.InterNetwork || ipAddress.AddressFamily == AddressFamily.InterNetworkV6) { callback(ipAddress); return; } throw new ArgumentException("This method will not currently resolve other than ipv4 addresses"); } // ok must be a host name IPHostEntry entry; try { Dns.BeginGetHostEntry(ipOrHost, delegate(IAsyncResult result) { try { entry = Dns.EndGetHostEntry(result); } catch (SocketException ex) { if (ex.SocketErrorCode == SocketError.HostNotFound) { //LogWrite(string.Format(CultureInfo.InvariantCulture, "Failed to resolve host '{0}'.", ipOrHost)); callback(null); return; } else { throw; } } if (entry == null) { callback(null); return; } // check each entry for a valid IP address foreach (var ipCurrent in entry.AddressList) { if (ipCurrent.AddressFamily == AddressFamily.InterNetwork || ipCurrent.AddressFamily == AddressFamily.InterNetworkV6) { callback(ipCurrent); return; } } callback(null); }, null); } catch (SocketException ex) { if (ex.SocketErrorCode == SocketError.HostNotFound) { //LogWrite(string.Format(CultureInfo.InvariantCulture, "Failed to resolve host '{0}'.", ipOrHost)); callback(null); } else { throw; } } }
public void Dns_BeginGetHostEntry_IPAddress_CallSocketInit_Ok() { NameResolutionPal.FakesReset(); Assert.ThrowsAny <Exception>(() => Dns.BeginGetHostEntry((IPAddress)null, null, null)); Assert.NotEqual(0, NameResolutionPal.FakesEnsureSocketsAreInitializedCallCount); }
void BeginGetHostEntry(string host) { SetStage(Stage.GettingHostEntry); Dns.BeginGetHostEntry(host, new AsyncCallback(HandleBeginGetHostEntry), null); }
public static IAsyncResult BeginGetHostEntry(string hostNameOrAddress, AsyncCallback requestCallback, object stateObject) { var asyncResult = Dns.BeginGetHostEntry(hostNameOrAddress, requestCallback, stateObject); return(asyncResult); }