Esempio n. 1
0
        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);
                listener.AddActivityTracking();

                var events = new ConcurrentQueue <(EventWrittenEventArgs Event, Guid ActivityId)>();
                await listener.RunWithCallbackAsync(e => events.Enqueue((e, e.ActivityId)), 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)));
                });

                VerifyEvents(events, InvalidHostName, 6, shouldHaveFailures: true);
            }).Dispose();
        }
        private void GetHostAddressCallback(IAsyncResult ar)
        {
            try
            {
                var param = (object[])ar.AsyncState;
                var host  = (string)param[0];
                var port  = (int)param[1];

                var results = Dns.EndGetHostAddresses(ar);

                var supportV4 = Socket.OSSupportsIPv4;
                var supportV6 = Socket.OSSupportsIPv6;
                var address   = results?.FirstOrDefault(d =>
                                                        d.AddressFamily == AddressFamily.InterNetwork && supportV4 ||
                                                        d.AddressFamily == AddressFamily.InterNetworkV6 && supportV6);

                if (address == null)
                {
                    Client.OnAfterServerConnected(Client.ServerReply.HostUnreachable);
                    return;
                }

                StartConnection(address, port);
            }
            catch (Exception)
            {
                // TODO: log

                Stop();
            }
        }
Esempio n. 3
0
        private void OnHostNameResolved(IAsyncResult ar)
        {
            object unrelatedObject = ar.AsyncState;

            IPAddress[] addresses = Dns.EndGetHostAddresses(ar);
            //Do something with addresses
        }
        protected void DnsGetHostAddressesCallback(IAsyncResult ar)
        {
            try {
                IPAddresses = Dns.EndGetHostAddresses(ar);
            }
            catch (SocketException e) {
                Debug.Print("ServerConnector.DnsGetHostAddressesCallback: Dns.EndGetHostAddresses threw SocketException:\n{0}", e);
                OnConnectionFailed(new InvalidOperationException("DNS lookup failed: Socket error occurred while resolving host name.", e));
                return;
            }
            catch (Exception e) {
                Debug.Print("ServerConnector.DnsGetHostAddressesCallback: Dns.EndGetHostAddresses threw unexpected exception:\n{0}", e);
                OnConnectionFailed(e);
                return;
            }

            try {
                EndPoints =
                    from ipAddress in IPAddresses
                    from port in Configuration.Ports
                    select new SslEndPoint(ipAddress, Math.Abs(port), (port < 0));
                EndPointEnumerator = EndPoints.GetEnumerator( );

                TryEstablishConnection( );
            }
            catch (Exception e) {
                Debug.Print("ServerConnector.DnsGetHostAddressesCallback: caught exception:\n{0}", e);
            }
        }
Esempio n. 5
0
        private void EndGetHostAddress(IAsyncResult asyncResult)
        {
            var state = (State)asyncResult.AsyncState;

            try
            {
                var addresses = Dns.EndGetHostAddresses(asyncResult);
                var endPoint  = new IPEndPoint(addresses[0], 123);

                var socket = new UdpClient();
                socket.Connect(endPoint);
                socket.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveTimeout, 500);
                socket.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.SendTimeout, 500);
                var sntpData = new byte[SntpDataLength];
                sntpData[0] = 0x1B;     // version = 4 & mode = 3 (client)

                var newState = new State(socket, endPoint, state.GetTime, state.Failure);
                var result   = socket.BeginSend(sntpData, sntpData.Length, EndSend, newState);
                RegisterWaitForTimeout(newState, result);
            }
            catch (Exception)
            {
                // retry, recursion stops at the end of the hosts
                BeginGetDate(state.GetTime, state.Failure);
            }
        }
Esempio n. 6
0
        private static void SetRemoteIPAsyncCallback(IAsyncResult ar)
        {
            SetRemoteIPRequestInfo setRemoteIPRequestInfo = (SetRemoteIPRequestInfo)ar.AsyncState;

            if (setRemoteIPRequestInfo.RequestId == _currentRequestId)
            {
                try
                {
                    bool        flag  = false;
                    IPAddress[] array = Dns.EndGetHostAddresses(ar);
                    for (int i = 0; i < array.Length; i++)
                    {
                        if (array[i].AddressFamily == AddressFamily.InterNetwork)
                        {
                            ServerIP     = array[i];
                            ServerIPText = setRemoteIPRequestInfo.RemoteAddress;
                            flag         = true;
                            break;
                        }
                    }
                    if (flag)
                    {
                        setRemoteIPRequestInfo.SuccessCallback();
                    }
                }
                catch (Exception)
                {
                }
            }
        }
Esempio n. 7
0
        public static IPAddress[] GetHostAddresses(string hostNameOrAddress, int timeout)
        {
            IPAddress[] addresses = null;
            using (var waitAsyncResult = new WaitAsyncResult((w, r) =>
            {
                try
                {
                    addresses = Dns.EndGetHostAddresses(r);
                    return(true);
                }
                catch (SystemException sex)
                {
                    if (g_traceInfo.IsWarningEnabled)
                    {
                        TraceHelper.TraceWarning(g_traceInfo, sex.Message);
                    }

                    return(false);
                }
            }))
            {
                Dns.BeginGetHostAddresses(hostNameOrAddress, waitAsyncResult.Callback, null);
                waitAsyncResult.Wait(timeout);
                return(addresses);
            }
        }
Esempio n. 8
0
        private void GetHostAddressesCallback(IAsyncResult ar)
        {
            // Make sure the request was still relevant
            if ((ar.AsyncState as string) != Text)
            {
                try
                {
                    _ = Dns.EndGetHostAddresses(ar);
                }
                catch { }
                return;
            }

            Resolving   = false;
            IpAddresses = null;
            try
            {
                IpAddresses = Dns.EndGetHostAddresses(ar).Where(a =>
                                                                a.AddressFamily == AddressFamily.InterNetwork ||
                                                                a.AddressFamily == AddressFamily.InterNetworkV6);
            }
            catch (SocketException) { }

            if (IpAddresses == null || !IpAddresses.Any())
            {
                OnResolveFailed(Text);
                ForeColor = ErrorForeColor;
                return;
            }

            ResolvedSuccessfully = true;
            OnResolveSuccessful(Text, IpAddresses);
        }
Esempio n. 9
0
        /// <summary>
        /// Create a new RPC client.
        /// </summary>
        /// <remarks>Note that creating a client object does not connect to the server -
        /// it simply gathers all the required information for future connections. </remarks>
        /// <param name="serverAddress">IP address or hostname of rpc server.</param>
        /// <param name="serverPort">Server port number.</param>
        /// <param name="timeout">Timeout (in ms) for all send and receive operations.</param>
        /// <exception cref="TimeoutException">Thown if unable to resolve hostname within 10 seconds.</exception>
        /// <exception cref="SocketException">Thownn if DNS lookup fails</exception>
        public RpcClient(string serverAddress, int serverPort, int timeout = 5000)
        {
            this.serverPort = serverPort;
            this.timeout    = timeout;
            if (!IPAddress.TryParse(serverAddress, out this.serverAddress))
            {
                // lookup hostname if we can't parse out an ip address
                var asyncDnsLookup = Dns.BeginGetHostAddresses(serverAddress, null, null);
                if (!asyncDnsLookup.AsyncWaitHandle.WaitOne(timeout))
                {
                    throw new TimeoutException("Unable to resolve hostname to IP address.");
                }
                var dnsResult = Dns.EndGetHostAddresses(asyncDnsLookup);
                this.serverAddress = dnsResult.Where(x => x.AddressFamily == AddressFamily.InterNetwork).FirstOrDefault();
                if (this.serverAddress == null)
                {
                    throw new ArgumentException("No IPv4 address for this hostname.");
                }
            }

            // handle binding redirection
            DirectoryInfo AssemblyDirectory = new FileInfo(typeof(RpcClient).Assembly.Location).Directory;

            resolver = new AssemblyRedirectResolver(AssemblyDirectory);

            AppDomain.CurrentDomain.AssemblyResolve += (s, e) => resolver.ResolveAssembly(e.Name, e.RequestingAssembly);
        }
Esempio n. 10
0
        public static void EventSource_ResolveValidHostName_LogsStartStop()
        {
            RemoteExecutor.Invoke(async() =>
            {
                const string ValidHostName = "microsoft.com";

                using var listener = new TestEventListener("System.Net.NameResolution", EventLevel.Informational);

                var events = new ConcurrentQueue <EventWrittenEventArgs>();
                await listener.RunWithCallbackAsync(events.Enqueue, async() =>
                {
                    await Dns.GetHostEntryAsync(ValidHostName);
                    await Dns.GetHostAddressesAsync(ValidHostName);

                    Dns.GetHostEntry(ValidHostName);
                    Dns.GetHostAddresses(ValidHostName);

                    Dns.EndGetHostEntry(Dns.BeginGetHostEntry(ValidHostName, null, null));
                    Dns.EndGetHostAddresses(Dns.BeginGetHostAddresses(ValidHostName, null, null));
                });

                Assert.DoesNotContain(events, e => e.EventId == 0); // errors from the EventSource itself

                Assert.True(events.Count >= 2 * 6);

                EventWrittenEventArgs[] starts = events.Where(e => e.EventName == "ResolutionStart").ToArray();
                Assert.Equal(6, starts.Length);
                Assert.All(starts, s => Assert.Equal(ValidHostName, Assert.Single(s.Payload).ToString()));

                EventWrittenEventArgs[] stops = events.Where(e => e.EventName == "ResolutionStop").ToArray();
                Assert.Equal(6, stops.Length);

                Assert.DoesNotContain(events, e => e.EventName == "ResolutionFailed");
            }).Dispose();
        }
Esempio n. 11
0
        /// <summary>
        /// Completes a pending asynchronous socket connection attempt.
        /// </summary>
        /// <param name="ar">The <see cref="IAsyncResult" /> instance returned by the initiating call to <see cref="BeginConnect" />.</param>
        /// <exception cref="SocketException">Thrown if the connection could not be establised.</exception>
        /// <remarks>
        /// <note>
        /// All successful calls to <see cref="BeginConnect" /> should be eventually matched with a call to <see cref="EndConnect" />.
        /// </note>
        /// </remarks>
        public void EndConnect(IAsyncResult ar)
        {
            lock (syncLock)
            {
                if (isTcp)
                {
                    sock.EndConnect(ar);
                }
                else
                {
                    var addresses = Dns.EndGetHostAddresses(ar);

                    sock.Bind();

                    udpRemoteEndPoint = new IPEndPoint(addresses[0], remoteBinding.Port);
                    isUdpConnected    = true;

                    // $hack(jeff.lill)
                    //
                    // This is a minor hack.  Instead of adding the additional complexity of transmitting the
                    // connection packet asynchronously, I'm just going to make a synchronous call here.  This
                    // shouldn't ever block in real life since the socket send buffer starts out empty.

                    sock.SendTo(udpConnectPacket, udpRemoteEndPoint);

                    udpConnectPacket = null;   // Don't need this any longer
                }
            }
        }
Esempio n. 12
0
        }         // func ResolveEndpointAsync

        private IPEndPoint EndResolveEndPoint(IAsyncResult ar)
        {
            var port      = (int)ar.AsyncState;
            var addresses = Dns.EndGetHostAddresses(ar);

            return(new IPEndPoint(addresses[0], port));
        }         // func EndResolveEndPoint
Esempio n. 13
0
        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

                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();
        }
Esempio n. 14
0
        /// <summary>
        /// 根据Dns获取到Ip地址后
        /// </summary>
        /// <param name="result">异步执行结果</param>
        private void OnDnsGetHostAddressesComplete(IAsyncResult result)
        {
            var payload = (InternalRuntime)result.AsyncState;

            try
            {
                var ipAddress = Dns.EndGetHostAddresses(result);

                client = Client ?? new UdpClient();

                serviceEndPoint = new IPEndPoint(ipAddress[0], remotePort);
                client.Connect(serviceEndPoint);
                InitKcp(conv);
                client.BeginReceive(OnReceiveCallBack, null);

                status = Status.Establish;
                Trigger(SocketEvents.Connect, this);
                payload.Result = true;
                payload.IsDone = true;
            }
            catch (Exception ex)
            {
                payload.Result = ex;
                payload.IsDone = true;
                Trigger(SocketEvents.Error, ex);
                Dispose();
            }
        }
Esempio n. 15
0
 private void EndGetHostAddresses(IAsyncResult ar)
 {
     lock (addresses)
     {
         try
         {
             int         port     = (int)ar.AsyncState;
             IPAddress[] newAddrs = Dns.EndGetHostAddresses(ar);
             {
                 //Preference IPv6
                 foreach (IPAddress newAddr in newAddrs)
                 {
                     if (newAddr.AddressFamily == AddressFamily.InterNetworkV6)
                     {
                         dnsReceived = true;
                         addresses.Add(new IPEndPoint(newAddr, port));
                     }
                 }
                 foreach (IPAddress newAddr in newAddrs)
                 {
                     if (newAddr.AddressFamily == AddressFamily.InterNetwork)
                     {
                         dnsReceived = true;
                         addresses.Add(new IPEndPoint(newAddr, port));
                     }
                 }
             }
         }
         catch (Exception e)
         {
             DarkLog.Debug("EndGetHostAddresses error: " + e);
         }
     }
 }
Esempio n. 16
0
 private static Task <IPAddress[]> GetHostAddressesAsync(string host)
 {
     return(Task.Factory.FromAsync(
                (c, s) => Dns.BeginGetHostAddresses(host, c, s),
                (r) => Dns.EndGetHostAddresses(r),
                null));
 }
Esempio n. 17
0
        public static void EventSource_ResolveValidHostName_LogsStartStop()
        {
            RemoteExecutor.Invoke(async() =>
            {
                const string ValidHostName = "microsoft.com";

                using var listener = new TestEventListener("System.Net.NameResolution", EventLevel.Informational);
                listener.AddActivityTracking();

                var events = new ConcurrentQueue <(EventWrittenEventArgs Event, Guid ActivityId)>();
                await listener.RunWithCallbackAsync(e => events.Enqueue((e, e.ActivityId)), async() =>
                {
                    await Dns.GetHostEntryAsync(ValidHostName);
                    await Dns.GetHostAddressesAsync(ValidHostName);

                    Dns.GetHostEntry(ValidHostName);
                    Dns.GetHostAddresses(ValidHostName);

                    Dns.EndGetHostEntry(Dns.BeginGetHostEntry(ValidHostName, null, null));
                    Dns.EndGetHostAddresses(Dns.BeginGetHostAddresses(ValidHostName, null, null));
                });

                VerifyEvents(events, ValidHostName, 6);
            }).Dispose();
        }
Esempio n. 18
0
        /// <summary>
        /// Async Get IPAdress
        /// </summary>
        /// <param name="host"></param>
        /// <param name="callback"></param>
        public static void GetIpAddress(string host, Action <IPAddress> callback = null)
        {
            IPAddress ipAddress = null;

            if (!IPAddress.TryParse(host, out ipAddress))
            {
                Dns.BeginGetHostAddresses(host, new AsyncCallback((asyncResult) =>
                {
                    IPAddress[] addrs = Dns.EndGetHostAddresses(asyncResult);
                    if (callback != null)
                    {
                        if (addrs.Length > 0)
                        {
                            ipAddress = addrs[0];
                        }
                        callback(ipAddress);
                    }
                }), null);
            }
            else
            {
                if (callback != null)
                {
                    callback(ipAddress);
                }
            }
        }
Esempio n. 19
0
 private static void SetRemoteIPAsyncCallback(IAsyncResult ar)
 {
     Netplay.SetRemoteIPRequestInfo asyncState = (Netplay.SetRemoteIPRequestInfo)ar.AsyncState;
     if (asyncState.RequestId != Netplay._currentRequestId)
     {
         return;
     }
     try
     {
         bool        flag          = false;
         IPAddress[] hostAddresses = Dns.EndGetHostAddresses(ar);
         for (int index = 0; index < hostAddresses.Length; ++index)
         {
             if (hostAddresses[index].AddressFamily == AddressFamily.InterNetwork)
             {
                 Netplay.ServerIP     = hostAddresses[index];
                 Netplay.ServerIPText = asyncState.RemoteAddress;
                 flag = true;
                 break;
             }
         }
         if (!flag)
         {
             return;
         }
         asyncState.SuccessCallback();
     }
     catch (Exception ex)
     {
     }
 }
Esempio n. 20
0
        public void DnsBeginGetHostAddresses_MachineName_MatchesGetHostAddresses()
        {
            IAsyncResult asyncObject = Dns.BeginGetHostAddresses(TestSettings.LocalHost, null, null);

            IPAddress[] results   = Dns.EndGetHostAddresses(asyncObject);
            IPAddress[] addresses = Dns.GetHostAddresses(TestSettings.LocalHost);
            Assert.Equal(addresses, results);
        }
Esempio n. 21
0
        private void GetHostAddressesTaskComplete(IAsyncResult ar)
        {
            try {
                UpdateIpAddressList(Dns.EndGetHostAddresses(ar));
            } catch {
            }

            GetHostAddressesSetup();
        }
Esempio n. 22
0
        private void OnHostResolve(IAsyncResult iar)
        {
            IPAddress[] host = null;
            try
            {
                host = Dns.EndGetHostAddresses(iar);

                // Check to make sure we got at least one IP address, otherwise we can stop right now.
                bool      gotOne = false;
                IPAddress ip     = null;
                bool      useIP6 = ConfigHelper.GetStringConfig("UseIPv6").ToLower() == "true";
                foreach (IPAddress addy in host)
                {
                    if (useIP6 ? addy.AddressFamily == AddressFamily.InterNetworkV6 : addy.AddressFamily == AddressFamily.InterNetwork)
                    {
                        gotOne = true;
                        ip     = addy;
                        break;
                    }
                }

                if (!gotOne)
                {
                    FireConnectedEvent(false, "Unable to resolve server IP Address.");
                }

                OnHostnameResolved(gotOne, ip);
                Log.LogMsg("Resolved host IP address to [" + ip + "]");

                IPEndPoint           ipep             = new IPEndPoint(ip, m_Port);
                SocketAsyncEventArgs connectEventArgs = CreateNewSaeaForConnect();
                MyTCPSocket = new Socket(useIP6 ? AddressFamily.InterNetworkV6 : AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                connectEventArgs.AcceptSocket = MyTCPSocket;

                MyTCPSocket.Bind(new IPEndPoint(useIP6 ? IPAddress.IPv6Any : IPAddress.Any, 0));

                //MyUDPSocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
                //MyUDPSocket.ExclusiveAddressUse = false;

                connectEventArgs.RemoteEndPoint = ipep;
                MyTCPSocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.KeepAlive, true);
                MyTCPSocket.SetSocketOption(SocketOptionLevel.Tcp, SocketOptionName.NoDelay, DisableTCPDelay);
                //MyTCPSocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.OutOfBandInline, true);

                Log.LogMsg("Connecting to host [" + ip + "] ...");
                bool willRaiseEvent = connectEventArgs.AcceptSocket.ConnectAsync(connectEventArgs);
                if (!willRaiseEvent)
                {
                    OnConnectionAttemptConcluded(connectEventArgs);
                }
            }
            catch (Exception e)
            {
                FireConnectedEvent(false, "Unable to resolve server IP Address. " + e.Message);
                return;
            }
        }
Esempio n. 23
0
        public void DnsBeginGetHostAddresses_BadIpString_ReturnsAddress()
        {
            IAsyncResult asyncObject = Dns.BeginGetHostAddresses("0.0.1.1", null, null);

            IPAddress[] results = Dns.EndGetHostAddresses(asyncObject);

            Assert.Equal(1, results.Length);
            Assert.Equal(IPAddress.Parse("0.0.1.1"), results[0]);
        }
Esempio n. 24
0
        private static void OnGetHostAddresses(IAsyncResult result)
        {
            var connectState = result.AsyncState as DnsConnectState;

            IPAddress[] addresses;

            try
            {
                addresses = Dns.EndGetHostAddresses(result);
            }
            catch
            {
                connectState.Callback(null, connectState.State, null);
                return;
            }

            if (addresses == null || addresses.Length <= 0)
            {
                connectState.Callback(null, connectState.State, null);
                return;
            }

            connectState.Addresses = addresses;

            CreateAttempSocket(connectState);

            Socket attempSocket;

            var address = GetNextAddress(connectState, out attempSocket);

            if (address == null)
            {
                connectState.Callback(null, connectState.State, null);
                return;
            }

            if (connectState.LocalEndPoint != null)
            {
                attempSocket.ExclusiveAddressUse = false;
                attempSocket.Bind(connectState.LocalEndPoint);
            }

            var socketEventArgs = new SocketAsyncEventArgs();

            socketEventArgs.Completed += new EventHandler <SocketAsyncEventArgs>(SocketConnectCompleted);
            var ipEndPoint = new IPEndPoint(address, connectState.Port);

            socketEventArgs.RemoteEndPoint = ipEndPoint;

            socketEventArgs.UserToken = connectState;

            if (!attempSocket.ConnectAsync(socketEventArgs))
            {
                SocketConnectCompleted(attempSocket, socketEventArgs);
            }
        }
Esempio n. 25
0
        private static void DNSAsyncCallbackTongcai(IAsyncResult ar)
        {
            int asyncState = (int)ar.AsyncState;

            IPAddress[] addressArray = Dns.EndGetHostAddresses(ar);
            if ((addressArray != null) && (addressArray.Length != 0))
            {
                ApolloConfig.loginOnlyIpTongCai = addressArray[0].ToString();
            }
        }
Esempio n. 26
0
        private static void OnHostNameResolved(IAsyncResult ar)
        {
            object unrelatedObject = ar.AsyncState;
            var    addresses       = Dns.EndGetHostAddresses(ar);

            foreach (var ipAddress in addresses)
            {
                Console.WriteLine(ipAddress);
            }
        }
Esempio n. 27
0
        // Called when the DNS query completes (either synchronously or asynchronously).  Checks for failure and
        // starts the first connection attempt if it succeeded.  Returns true if the operation will be asynchronous,
        // false if it has failed synchronously.
        private bool DoDnsCallback(IAsyncResult result, bool sync)
        {
            Exception exception = null;

            lock (lockObject)
            {
                // If the connection attempt was canceled during the dns query, the user's callback has already been
                // called asynchronously and we simply need to return.
                if (state == State.Canceled)
                {
                    return(true);
                }

                GlobalLog.Assert(state == State.DnsQuery, "MultipleConnectAsync.DoDnsCallback(): Unexpected object state");

                try
                {
                    addressList = Dns.EndGetHostAddresses(result);
                    GlobalLog.Assert(addressList != null, "MultipleConnectAsync.DoDnsCallback(): EndGetHostAddresses returned null!");
                }
                catch (Exception e)
                {
                    state     = State.Completed;
                    exception = e;
                }

                // If the dns query succeeded, try to connect to the first address
                if (exception == null)
                {
                    state = State.ConnectAttempt;

                    internalArgs            = new SocketAsyncEventArgs();
                    internalArgs.Completed += InternalConnectCallback;
                    internalArgs.SetBuffer(userArgs.Buffer, userArgs.Offset, userArgs.Count);

                    exception = AttemptConnection();

                    if (exception != null)
                    {
                        // There was a synchronous error while connecting
                        state = State.Completed;
                    }
                }
            }

            // Call this outside of the lock because it might call the user's callback.
            if (exception != null)
            {
                return(Fail(sync, exception));
            }
            else
            {
                return(true);
            }
        }
        private static void DNSAsyncCallback(IAsyncResult ar)
        {
            int num = (int)ar.get_AsyncState();

            IPAddress[] array = Dns.EndGetHostAddresses(ar);
            if (array == null || array.Length == 0)
            {
                return;
            }
            ApolloConfig.loginOnlyIp = array[0].ToString();
        }
Esempio n. 29
0
        static void LookupHostName2()
        {
            //le variaibli vengono catturate
            //si perde però ogni possibilità di gestire eventuali accezioni

            Dns.BeginGetHostAddresses("www.elfo.net", ar =>
            {
                Dns.EndGetHostAddresses(ar).ToList().ForEach(Console.WriteLine);
            },
                                      null);
        }
        private static void OnGetHostAddresses(IAsyncResult result)
        {
            DnsConnectState dnsConnectState = result.AsyncState as DnsConnectState;

            IPAddress[] array;
            try
            {
                array = Dns.EndGetHostAddresses(result);
            }
            catch (Exception exception)
            {
                dnsConnectState.Callback(null, dnsConnectState.State, null, exception);
                return;
            }
            if (array == null || array.Length == 0)
            {
                dnsConnectState.Callback(null, dnsConnectState.State, null, new SocketException(11001));
                return;
            }
            dnsConnectState.Addresses = array;
            CreateAttempSocket(dnsConnectState);
            Socket    attempSocket;
            IPAddress nextAddress = GetNextAddress(dnsConnectState, out attempSocket);

            if (nextAddress == null)
            {
                dnsConnectState.Callback(null, dnsConnectState.State, null, new SocketException(10047));
                return;
            }
            if (dnsConnectState.LocalEndPoint != null)
            {
                try
                {
                    attempSocket.ExclusiveAddressUse = false;
                    attempSocket.Bind(dnsConnectState.LocalEndPoint);
                }
                catch (Exception exception2)
                {
                    dnsConnectState.Callback(null, dnsConnectState.State, null, exception2);
                    return;
                }
            }
            SocketAsyncEventArgs socketAsyncEventArgs = new SocketAsyncEventArgs();

            socketAsyncEventArgs.Completed += SocketConnectCompleted;
            IPEndPoint iPEndPoint = (IPEndPoint)(socketAsyncEventArgs.RemoteEndPoint = new IPEndPoint(nextAddress, dnsConnectState.Port));

            socketAsyncEventArgs.UserToken = dnsConnectState;
            if (!attempSocket.ConnectAsync(socketAsyncEventArgs))
            {
                SocketConnectCompleted(attempSocket, socketAsyncEventArgs);
            }
        }