/// <summary>
        /// GetHostAddresses with timeout.
        /// </summary>
        /// <param name="host">Host name.</param>
        /// <param name="timeoutMillis">Timeout in milliseconds</param>
        public static IPAddress[] GetHostAddresses(string host, int timeoutMillis)
        {
            IAsyncResult result = Dns.BeginGetHostAddresses(host, null, null);
            WaitHandle   wait   = result.AsyncWaitHandle;

            if (wait.WaitOne(timeoutMillis))
            {
                // EndGetHostAddresses will automatically close AsyncWaitHandle.
                IPAddress[] addresses = Dns.EndGetHostAddresses(result);

                if (addresses.Length == 0)
                {
                    throw new AerospikeException.Connection("Failed to find addresses for " + host);
                }
                return(addresses);
            }
            else
            {
                // Do not close AsyncWaitHandle because the disposed handle can be referenced after
                // the exception is thrown. The handle will eventually get closed by the garbage collector.
                // See: https://social.msdn.microsoft.com/Forums/en-US/313cf28c-2a6d-498e-8188-7a0639dbd552/tcpclientbeginconnect-issue?forum=netfxnetcom
                throw new AerospikeException.Connection("Failed to resolve " + host);
            }
        }
Example #2
0
 public void BeginGetDate(Action <DateTime> getTime, Action failure)
 {
     index += 1;
     if (hosts.Length <= index)
     {
         if (hosts.Length == index)
         {
             failure();
         }
         return;
     }
     try
     {
         var host   = hosts[index];
         var state  = new State(null, null, getTime, failure);
         var result = Dns.BeginGetHostAddresses(host, EndGetHostAddress, state);
         RegisterWaitForTimeout(state, result);
     }
     catch (Exception)
     {
         // retry, recursion stops at the end of the hosts
         BeginGetDate(getTime, failure);
     }
 }
Example #3
0
        public void BeginGetHostAddresses_HostNameOrAddress_UnspecifiedAddress()
        {
            // IPv4
            try {
                Dns.BeginGetHostAddresses(
                    "0.0.0.0",
                    new AsyncCallback(GetHostAddressesCallback),
                    null);
                Assert.Fail("#A1");
            } 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(), "#A2");
                Assert.IsNull(ex.InnerException, "#A3");
                Assert.IsNotNull(ex.Message, "#A4");
                Assert.AreEqual("hostNameOrAddress", ex.ParamName, "#A5");
            }

            // IPv6
            try {
                Dns.BeginGetHostAddresses(
                    "::0",
                    new AsyncCallback(GetHostAddressesCallback),
                    null);
                Assert.Fail("#B1");
            } 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(), "#B2");
                Assert.IsNull(ex.InnerException, "#B3");
                Assert.IsNotNull(ex.Message, "#B4");
                Assert.AreEqual("hostNameOrAddress", ex.ParamName, "#B5");
            }
        }
Example #4
0
 public void Connect(string hostname, int port)
 {
     if (ConnectTimeout > TimeSpan.Zero)
     {
         // https://forum.unity3d.com/threads/best-http-released.200006/page-37#post-3150972
         System.Threading.ManualResetEvent mre = new System.Threading.ManualResetEvent(false);
         IAsyncResult result  = Dns.BeginGetHostAddresses(hostname, (res) => mre.Set(), null);
         bool         success = mre.WaitOne(ConnectTimeout);
         if (success)
         {
             IPAddress[] addresses = Dns.EndGetHostAddresses(result);
             Connect(addresses, port);
         }
         else
         {
             throw new TimeoutException("DNS resolve timed out!");
         }
     }
     else
     {
         IPAddress[] addresses = Dns.GetHostAddresses(hostname);
         Connect(addresses, port);
     }
 }
Example #5
0
        public static void LookupHostName(string hostName)
        {
            object unrelatedObject = "object";

            Dns.BeginGetHostAddresses(hostName, OnHostNameResolved, unrelatedObject);
        }
Example #6
0
 public IAsyncResult BeginGetHostEndpoints(AsyncCallback requestCallback, object state)
 {
     return(Dns.BeginGetHostAddresses(_hostname, requestCallback, state));
 }
Example #7
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)
        {
            // TODO Eliminate sync variant, and implement timeout

#if FEATURE_DNS_SYNC
            return(Dns.GetHostAddresses(hostNameOrAddress));
#elif FEATURE_DNS_APM
            var asyncResult = Dns.BeginGetHostAddresses(hostNameOrAddress, null, null);
            if (!asyncResult.AsyncWaitHandle.WaitOne(Session.InfiniteTimeSpan))
            {
                throw new SshOperationTimeoutException("Timeout resolving host name.");
            }
            return(Dns.EndGetHostAddresses(asyncResult));
#elif FEATURE_DNS_TAP
            return(Dns.GetHostAddressesAsync(hostNameOrAddress).GetAwaiter().GetResult());
#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
        }
    }
Example #8
0
        private static void LookupHostName()
        {
            object unrelatedObject = "hello";

            Dns.BeginGetHostAddresses("oreilly.com", OnHostNameResolved, unrelatedObject);
        }
        public bool ReconnectToNewHost(string serverIp, int serverPort)
        {
            bool result;

            if (!NetworkClient.active)
            {
                if (LogFilter.logError)
                {
                    Debug.LogError("Reconnect - NetworkClient must be active");
                }
                result = false;
            }
            else if (this.m_Connection == null)
            {
                if (LogFilter.logError)
                {
                    Debug.LogError("Reconnect - no old connection exists");
                }
                result = false;
            }
            else
            {
                if (LogFilter.logInfo)
                {
                    Debug.Log(string.Concat(new object[]
                    {
                        "NetworkClient Reconnect ",
                        serverIp,
                        ":",
                        serverPort
                    }));
                }
                ClientScene.HandleClientDisconnect(this.m_Connection);
                ClientScene.ClearLocalPlayers();
                this.m_Connection.Disconnect();
                this.m_Connection = null;
                this.m_ClientId   = NetworkTransport.AddHost(this.m_HostTopology, this.m_HostPort);
                this.m_ServerPort = serverPort;
                if (Application.platform == RuntimePlatform.WebGLPlayer)
                {
                    this.m_ServerIp     = serverIp;
                    this.m_AsyncConnect = NetworkClient.ConnectState.Resolved;
                }
                else if (serverIp.Equals("127.0.0.1") || serverIp.Equals("localhost"))
                {
                    this.m_ServerIp     = "127.0.0.1";
                    this.m_AsyncConnect = NetworkClient.ConnectState.Resolved;
                }
                else
                {
                    if (LogFilter.logDebug)
                    {
                        Debug.Log("Async DNS START:" + serverIp);
                    }
                    this.m_AsyncConnect = NetworkClient.ConnectState.Resolving;
                    Dns.BeginGetHostAddresses(serverIp, new AsyncCallback(NetworkClient.GetHostAddressesCallback), this);
                }
                result = true;
            }
            return(result);
        }
Example #10
0
        public bool ReconnectToNewHost(string serverIp, int serverPort)
        {
            if (!NetworkClient.active)
            {
                if (LogFilter.logError)
                {
                    Debug.LogError("Reconnect - NetworkClient must be active");
                }
                return(false);
            }

            if (m_Connection == null)
            {
                if (LogFilter.logError)
                {
                    Debug.LogError("Reconnect - no old connection exists");
                }
                return(false);
            }

            if (LogFilter.logInfo)
            {
                Debug.Log("NetworkClient Reconnect " + serverIp + ":" + serverPort);
            }

            ClientScene.HandleClientDisconnect(m_Connection);
            ClientScene.ClearLocalPlayers();

            m_Connection.Disconnect();
            m_Connection = null;
            m_ClientId   = NetworkTransport.AddHost(m_HostTopology, 0);

            string hostnameOrIp = serverIp;

            m_ServerPort = serverPort;

            //TODO: relay reconnect

            /*
             * if (Match.NetworkMatch.matchSingleton != null)
             * {
             *  hostnameOrIp = Match.NetworkMatch.matchSingleton.address;
             *  m_ServerPort = Match.NetworkMatch.matchSingleton.port;
             * }*/

            if (UnityEngine.Application.platform == RuntimePlatform.WebGLPlayer)
            {
                m_ServerIp     = hostnameOrIp;
                m_AsyncConnect = ConnectState.Resolved;
            }
            else if (serverIp.Equals("127.0.0.1") || serverIp.Equals("localhost"))
            {
                m_ServerIp     = "127.0.0.1";
                m_AsyncConnect = ConnectState.Resolved;
            }
            else
            {
                if (LogFilter.logDebug)
                {
                    Debug.Log("Async DNS START:" + hostnameOrIp);
                }
                m_AsyncConnect = ConnectState.Resolving;
                Dns.BeginGetHostAddresses(hostnameOrIp, new AsyncCallback(GetHostAddressesCallback), this);
            }
            return(true);
        }
Example #11
0
 private void checkHostEntry(HostChanger.hostEntry entry)
 {
     Dns.BeginGetHostAddresses(entry.hostname, new AsyncCallback(ProcessHostEntries), entry);
 }
Example #12
0
        private void toGetDNS()
        {
            _state       = Connecting;
            _connectTime = 0;

            int index = ++_doIndex;

            _currentInfo = _ipInfoDic.get(_host);

            if (_currentInfo != null)
            {
                preConnectAfterAddress();
            }
            else
            {
                IPAddress address;

                if (!IPAddress.TryParse(_host, out address))
                {
                    Ctrl.debugLog("dns上");

                    Dns.BeginGetHostAddresses(_host, v =>
                    {
                        IPAddress[] addresses = null;

                        try
                        {
                            addresses = Dns.EndGetHostAddresses(v);
                        }
                        catch (Exception e)
                        {
                            Ctrl.printExceptionForIO(e);
                        }

                        ThreadControl.addMainFunc(() =>
                        {
                            if (index == _doIndex)
                            {
                                if (addresses != null)
                                {
                                    foreach (IPAddress ipAddress in addresses)
                                    {
                                        Ctrl.print("dns看收到的上地址", ipAddress);
                                    }

                                    _currentInfo = registIPInfo(_host, addresses);
                                    preConnectAfterAddress();
                                }
                                else
                                {
                                    Ctrl.printForIO("解析dns失败");
                                }
                            }
                            else
                            {
                                Ctrl.print("dns获取完,已经到下个index");
                            }
                        });
                    }, null);
                }
                else
                {
                    Ctrl.debugLog("dns下");
                    _currentInfo = registIPInfo(_host, new[] { address });
                    preConnectAfterAddress();
                }
            }
        }
Example #13
0
        private byte TCPIP_DNS_Q()
        {
            var flags = cpu.Registers.B;

            if (flags.GetBit(2) == 1 && dnsQueryInProgress)
            {
                return(ERR_QUERY_EXISTS);
            }
            if (flags.GetBit(0) == 1)
            {
                dnsQueryInProgress = false;
                lastDnsError       = 0;
                return(ERR_OK);
            }

            if (NoNetworkAvailable())
            {
                return(ERR_NO_NETWORK);
            }

            if (!dnsServersAvailable)
            {
                return(ERR_NO_DNS);
            }

            var namePointer = cpu.Registers.HL;
            var nameBytes   = new List <byte>();

            while (slots[namePointer] != 0)
            {
                nameBytes.Add(slots[namePointer++]);
            }
            var name = Encoding.ASCII.GetString(nameBytes.ToArray());

            var wasIp = IPAddress.TryParse(name, out IPAddress parsedIp) &&
                        IsIPv4(parsedIp);

            if (wasIp)
            {
                lastIpResolved            = parsedIp.GetAddressBytes();
                lastIpResolvedWasDirectIp = true;
                cpu.Registers.B           = 1;
                cpu.Registers.L           = lastIpResolved[0];
                cpu.Registers.H           = lastIpResolved[1];
                cpu.Registers.E           = lastIpResolved[2];
                cpu.Registers.D           = lastIpResolved[3];

                return(ERR_OK);
            }

            if (flags.GetBit(1) == 1)
            {
                return(ERR_INV_IP);
            }

            dnsQueryInProgress = true;
            Dns.BeginGetHostAddresses(name,
                                      ar =>
            {
                dnsQueryInProgress = false;
                IPAddress[] addresses;
                try
                {
                    addresses = Dns.EndGetHostAddresses(ar);
                }
                catch (Exception ex)
                {
                    if (ex is SocketException sockEx)
                    {
                        lastDnsError = UnapiDnsErrorFromSocketError(sockEx.SocketErrorCode);
                    }
                    else
                    {
                        lastDnsError = 0;
                    }

                    return;
                }
                var address               = addresses.FirstOrDefault(IsIPv4);
                lastIpResolved            = address?.GetAddressBytes();
                lastIpResolvedWasDirectIp = false;
                lastDnsError              = null;
            }
                                      , null);

            cpu.Registers.B = 0;
            return(ERR_OK);
        }
Example #14
0
 private void StartDnsResolve(DnsResolveStatus rs)
 {
     Dns.BeginGetHostAddresses(rs.Hostname, new AsyncCallback(DnsCallback), rs);
 }
Example #15
0
        public MumbleClient(string hostName, int port, AudioPlayerCreatorMethod createMumbleAudioPlayerMethod,
                            AudioPlayerRemoverMethod removeMumbleAudioPlayerMethod, AnyUserStateChangedMethod anyChangeMethod = null,
                            bool async            = false, SpeakerCreationMode speakerCreationMode = SpeakerCreationMode.ALL,
                            DebugValues debugVals = null, int maxPositionalDataLength              = 0)
        {
            _hostName                = hostName;
            _port                    = port;
            _audioPlayerCreator      = createMumbleAudioPlayerMethod;
            _audioPlayerDestroyer    = removeMumbleAudioPlayerMethod;
            _speakerCreationMode     = speakerCreationMode;
            _anyUserStateChange      = anyChangeMethod;
            _maxPositionalDataLength = maxPositionalDataLength;

            //Check if localhost
            if (_hostName.ToLower() == "localhost")
            {
                _hostName = "127.0.0.1";
            }

            switch (AudioSettings.outputSampleRate)
            {
            case 8000:
            case 12000:
            case 16000:
            case 24000:
            case 48000:
                _outputSampleRate = AudioSettings.outputSampleRate;
                break;

            default:
                Debug.LogError("Incorrect sample rate of:" + AudioSettings.outputSampleRate + ". It should be 48000 please set this in Edit->Audio->SystemSampleRate");
                _outputSampleRate = 48000;
                break;
            }
            Debug.Log("Using output sample rate: " + _outputSampleRate);

            switch (AudioSettings.speakerMode)
            {
            case AudioSpeakerMode.Mono:
                // TODO sometimes, even though the speaker mode is mono,
                // on audiofilterread wants two channels
                _outputChannelCount = 1;
                break;

            case AudioSpeakerMode.Stereo:
                _outputChannelCount = 2;
                break;

            default:
                Debug.LogError("Unsupported speaker mode " + AudioSettings.speakerMode + " please set this in Edit->Audio->DefaultSpeakerMode to either Mono or Stereo");
                _outputChannelCount = 2;
                break;
            }
            Debug.Log("Using output channel count of: " + _outputChannelCount);

            if (debugVals == null)
            {
                debugVals = new DebugValues();
            }
            _debugValues = debugVals;

            if (async)
            {
                Dns.BeginGetHostAddresses(hostName, OnHostRecv, null);
            }
            else
            {
                IPAddress[] addresses = Dns.GetHostAddresses(hostName);
                Init(addresses);
            }
        }
Example #16
0
        public Task <DateTime> GetDateAsync()
        {
            index++;
            if (hosts.Length <= index)
            {
                throw new InvalidOperationException(
                          "After trying out all the hosts, was unable to find anyone that could tell us what the time is");
            }
            var host = hosts[index];

            return(Task.Factory.FromAsync <IPAddress[]>((callback, state) => Dns.BeginGetHostAddresses(host, callback, state),
                                                        Dns.EndGetHostAddresses, host)
                   .ContinueWith(hostTask =>
            {
                if (hostTask.IsFaulted)
                {
                    log.DebugException("Could not get time from: " + host, hostTask.Exception);
                    return GetDateAsync();
                }
                var endPoint = new IPEndPoint(hostTask.Result[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)
                return Task.Factory.FromAsync <int>(
                    (callback, state) => socket.BeginSend(sntpData, sntpData.Length, callback, state),
                    socket.EndSend, null)
                .ContinueWith(sendTask =>
                {
                    if (sendTask.IsFaulted)
                    {
                        try
                        {
                            socket.Close();
                        }
                        catch (Exception)
                        {
                        }
                        log.DebugException("Could not send time request to : " + host, sendTask.Exception);
                        return GetDateAsync();
                    }

                    return Task.Factory.FromAsync <byte[]>(socket.BeginReceive, (ar) => socket.EndReceive(ar, ref endPoint), null)
                    .ContinueWith(receiveTask =>
                    {
                        if (receiveTask.IsFaulted)
                        {
                            try
                            {
                                socket.Close();
                            }
                            catch (Exception)
                            {
                            }
                            log.DebugException("Could not get time response from: " + host, receiveTask.Exception);
                            return GetDateAsync();
                        }
                        var result = receiveTask.Result;
                        if (IsResponseValid(result) == false)
                        {
                            log.Debug("Did not get valid time information from " + host);
                            return GetDateAsync();
                        }
                        var transmitTimestamp = GetTransmitTimestamp(result);
                        return new CompletedTask <DateTime>(transmitTimestamp);
                    }).Unwrap();
                }).Unwrap();
            }).Unwrap());
        }
Example #17
0
        IEnumerator _Send()
        {
            ++_sent;

            var bytes = Crypto.RandomBytes(_size);

            // resolve
            if (_hostEntry == null)
            {
                var dns = Dns.BeginGetHostAddresses(_host, null, null);
                while (!dns.IsCompleted)
                {
                    yield return(null);
                }

                try {
                    var ips = Dns.EndGetHostAddresses(dns);

                    if (EB.Net.TcpClientUtil.OSSupportsIPv4())
                    {
                        foreach (var ip in ips)
                        {
                            if (ip.AddressFamily == AddressFamily.InterNetwork)
                            {
                                _hostEntry = ip;
                                break;
                            }
                        }
                    }

                    if (_hostEntry == null && EB.Net.TcpClientUtil.OSSupportsIPv6())
                    {
                        foreach (var ip in ips)
                        {
                            if (ip.AddressFamily == AddressFamily.InterNetworkV6)
                            {
                                _hostEntry = ip;
                                break;
                            }
                        }
                    }
                }
                catch {
                }
            }

            if (_hostEntry == null)
            {
                if (OnError != null)
                {
                    OnError(Localizer.GetString("ID_SPARX_ERROR_FAILED_DNS"));
                    yield break;
                }
            }

            // check address family
            if (_client.Client.AddressFamily != _hostEntry.AddressFamily)
            {
                int bindPort = ((IPEndPoint)_client.Client.LocalEndPoint).Port;
                _client.Close();
                _client = null;

                // find a bind port
                while (_client == null)
                {
                    try
                    {
                        _client = new UdpClient(bindPort, _hostEntry.AddressFamily);
                    }
                    catch
                    {
                        bindPort++;
                    }
                }

                EB.Debug.Log("QosProbe Re-Bound to " + bindPort + " for  " + _host);
            }

            // get the ip
            var ep = new IPEndPoint(_hostEntry, _port);

            try {
                _client.Send(bytes, bytes.Length, ep);
            }
            catch {
                OnError(Localizer.GetString("ID_SPARX_ERROR_UNKNOWN"));
                yield break;
            }

            var ping  = 0.0f;
            var start = System.DateTime.Now;

            var async = _client.BeginReceive(delegate(System.IAsyncResult ar){
                ping = (float)(System.DateTime.Now - start).TotalMilliseconds;
                //Debug.Log("receive complete " + ping + " " + _host);
            }, null);


            var timeout = Time.realtimeSinceStartup + _timeout / 1000.0f;

            while (!async.IsCompleted)
            {
                if (Time.realtimeSinceStartup >= timeout)
                {
                    // we timed out;
                    EB.Debug.LogWarning("QosProbe timed out to " + _host);
                    yield return(new WaitForFixedUpdate());

                    SendProbe();
                    yield break;
                }
                yield return(null);
            }

            _received++;
            _data = _client.EndReceive(async, ref ep);

            _sum += ping;
            _max  = Mathf.Max(_max, ping);
            _min  = Mathf.Min(_min, ping);

            SendProbe();
        }
Example #18
0
 static void Main(string[] args)
 {
     Dns.BeginGetHostAddresses("www.baidu.com", result => { IPAddress[] address = Dns.EndGetHostAddresses(result); Console.WriteLine(address[0]); }, null);
     Console.ReadLine();
 }
Example #19
0
        //si basa su IAsyncResult

        //1. il chiamante invoca il metodo Begin passando una callback
        //2. l'operazione avviene in un thread separato
        //3. al termine dell'operazione viene richiamata la callback
        //4. il chiamante esegue il metodo End che restituisce il risultato

        private static void LookupHostName1()
        {
            Dns.BeginGetHostAddresses("www.elfo.net", OnHostNameResolved, null);
        }
Example #20
0
 /// <summary>
 /// Construct a new client where the address or host name of
 /// the server is known.
 /// </summary>
 /// <param name="hostNameOrAddress">The host name or address of the server</param>
 /// <param name="port">The port of the server</param>
 public TcpReceiverClient(string hostNameOrAddress, int port)
     : this(port)
 {
     addressesSet = new AutoResetEvent(false);
     Dns.BeginGetHostAddresses(hostNameOrAddress, GetHostAddressesCallback, null);
 }
Example #21
0
        public override void Open(NpgsqlConnector context, Int32 timeout)
        {
            try
            {
                NpgsqlEventLog.LogMethodEnter(LogLevel.Debug, CLASSNAME, "Open");

                IAsyncResult result;
                // Keep track of time remaining; Even though there may be multiple timeout-able calls,
                // this allows us to still respect the caller's timeout expectation.
                DateTime attemptStart;

                attemptStart = DateTime.Now;

                result = Dns.BeginGetHostAddresses(context.Host, null, null);

                if (!result.AsyncWaitHandle.WaitOne(timeout, true))
                {
                    // Timeout was used up attempting the Dns lookup
                    throw new TimeoutException("Exception_DnsLookupTimeout");
                }

                timeout -= Convert.ToInt32((DateTime.Now - attemptStart).TotalMilliseconds);

                IPAddress[] ips    = Dns.EndGetHostAddresses(result);
                Socket      socket = null;
                Exception   lastSocketException = null;

                // try every ip address of the given hostname, use the first reachable one
                // make sure not to exceed the caller's timeout expectation by splitting the
                // time we have left between all the remaining ip's in the list.
                for (int i = 0; i < ips.Length; i++)
                {
                    NpgsqlEventLog.LogMsg("Log_ConnectingTo", LogLevel.Debug, ips[i]);

                    IPEndPoint ep = new IPEndPoint(ips[i], context.Port);
                    socket = new Socket(ep.AddressFamily, SocketType.Stream, ProtocolType.Tcp);

                    attemptStart = DateTime.Now;

                    try
                    {
                        result = socket.BeginConnect(ep, null, null);

                        if (!result.AsyncWaitHandle.WaitOne(timeout / (ips.Length - i), true))
                        {
                            throw new TimeoutException("Exception_ConnectionTimeout");
                        }

                        socket.EndConnect(result);

                        // connect was successful, leave the loop
                        break;
                    }
                    catch (Exception e)
                    {
                        NpgsqlEventLog.LogMsg("Log_FailedConnection", LogLevel.Normal, ips[i]);

                        timeout            -= Convert.ToInt32((DateTime.Now - attemptStart).TotalMilliseconds);
                        lastSocketException = e;

                        socket.Close();
                        socket = null;
                    }
                }

                if (socket == null)
                {
                    throw lastSocketException;
                }

                NpgsqlNetworkStream baseStream = new NpgsqlNetworkStream(socket, true);
                Stream sslStream = null;

                // If the PostgreSQL server has SSL connectors enabled Open SslClientStream if (response == 'S') {
                if (context.SSL || (context.SslMode == SslMode.Require) || (context.SslMode == SslMode.Prefer))
                {
                    baseStream
                    .WriteInt32(8)
                    .WriteInt32(80877103);

                    throw new InvalidOperationException("Exception_Ssl_RequestError");
                }

                context.Socket     = socket;
                context.BaseStream = baseStream;
                context.Stream     = new BufferedStream(sslStream == null ? baseStream : sslStream, 8192);

                NpgsqlEventLog.LogMsg("Log_ConnectedTo", LogLevel.Normal, context.Host, context.Port);
                ChangeState(context, NpgsqlConnectedState.Instance);
            }
            catch (Exception e)
            {
                throw new NpgsqlException("Exception_FailedConnection", e);
            }
        }
Example #22
0
        public void DnsBeginGetHostAddresses_BadName_Throws()
        {
            IAsyncResult asyncObject = Dns.BeginGetHostAddresses("BadName", null, null);

            Assert.ThrowsAny <SocketException>(() => Dns.EndGetHostAddresses(asyncObject));
        }
Example #23
0
        // Network Thread
        private void UpdateStun()
        {
            bool didPoll = stunRequestedCount > 0;

            double now = NetTime.Now;

            if (now > stunExpireTime)
            {
                stunResult     = null;
                stunInProgress = false;

                if (didPoll)
                {
                    if (stunHostnames.Count == 0)
                    {
                        return;
                    }

                    // Restart STUN
                    stunInProgress = true;
                    stunExpireTime = now + Configuration.AssumedNATMappingTime; // <- When do we give up querying?

                    if (pendingStun == null)
                    {
                        pendingStun = new StunInfo[stunHostnames.Count];
                    }
                    else
                    {
                        Array.Clear(pendingStun, 0, pendingStun.Length);
                    }

                    var rng = StunRNG;

                    for (int i = 0; i < pendingStun.Length; i++)
                    {
                        // NOTE: Retransmit values are specified in RFC 5389
                        pendingStun[i].remainingTransmits  = 7;
                        pendingStun[i].nextRetransmitDelay = 0.5;
                        pendingStun[i].nextTransmitTime    = double.NegativeInfinity;

                        pendingStun[i].transactionID0 = rng.NextUInt();
                        pendingStun[i].transactionID1 = rng.NextUInt();
                        pendingStun[i].transactionID2 = rng.NextUInt();
                    }

                    stunStartedCount = 1; // <- Cause the first request to start
                }
            }

            if (stunInProgress)
            {
                int liveStunCount = 0;

                for (int i = 0; i < stunStartedCount; i++)
                {
                    if (pendingStun[i].dead)
                    {
                        goto finish;
                    }

                    // STEP 1: Start a DNS query
                    if (pendingStun[i].endpoint == null && pendingStun[i].pendingDnsRequest == null)
                    {
                        try
                        {
                            pendingStun[i].pendingDnsRequest = Dns.BeginGetHostAddresses(stunHostnames[i], null, null);
                        }
                        catch
                        {
                            LogDebug("STUN BeginGetHostAddresses failed for \"" + stunHostnames[i] + "\"");
                            pendingStun[i].dead = true;
                            goto finish;
                        }
                    }

                    // STEP 2: Finish DNS query
                    bool firstTransmit = false;
                    if (pendingStun[i].pendingDnsRequest != null && pendingStun[i].pendingDnsRequest.IsCompleted)
                    {
                        try
                        {
                            var       addresses   = Dns.EndGetHostAddresses(pendingStun[i].pendingDnsRequest);
                            IPAddress bestAddress = null;
                            foreach (var address in addresses)
                            {
                                if (address.AddressFamily != AddressFamily.InterNetwork && address.AddressFamily != AddressFamily.InterNetworkV6)
                                {
                                    continue;
                                }

                                // TODO: How to preference IPv4 vs IPv6 (for now, always prefer IPv4)
                                if (bestAddress == null || bestAddress.AddressFamily == AddressFamily.InterNetworkV6 && address.AddressFamily == AddressFamily.InterNetwork)
                                {
                                    bestAddress = address;
                                }
                            }

                            if (bestAddress == null)
                            {
                                LogDebug("STUN No address result for \"" + stunHostnames[i] + "\"");
                                pendingStun[i].dead = true;
                                goto finish;
                            }

                            pendingStun[i].endpoint = new IPEndPoint(bestAddress, stunPorts[i]);
                        }
                        catch
                        {
                            LogDebug("STUN EndGetHostAddresses failed for \"" + stunHostnames[i] + "\"");
                            pendingStun[i].dead = true;
                            goto finish;
                        }
                        finally
                        {
                            Debug.Assert(pendingStun[i].endpoint != null || pendingStun[i].dead);
                            pendingStun[i].pendingDnsRequest = null;
                        }

                        Debug.Assert(pendingStun[i].endpoint != null);
                        firstTransmit = true;
                    }

                    // STEP 3: Generate and transmit STUN requests
                    if (pendingStun[i].endpoint != null)
                    {
                        if (now >= pendingStun[i].nextTransmitTime)
                        {
                            // Use retransmit as a trigger to fail-over to the next STUN
                            if (!firstTransmit && i == stunStartedCount - 1 && stunStartedCount < pendingStun.Length)
                            {
                                stunStartedCount++;
                            }

                            if (pendingStun[i].remainingTransmits > 0)
                            {
                                pendingStun[i].remainingTransmits--;
                                pendingStun[i].nextTransmitTime     = now + pendingStun[i].nextRetransmitDelay;
                                pendingStun[i].nextRetransmitDelay *= 2.0;

                                LogVerbose("STUN Sending packet to \"" + stunHostnames[i] + "\" at " + pendingStun[i].endpoint + " (remain="
                                           + pendingStun[i].remainingTransmits + "; delay=" + pendingStun[i].nextRetransmitDelay + ")");

                                if (!SendStunPacket(pendingStun[i].endpoint, pendingStun[i].transactionID0, pendingStun[i].transactionID1, pendingStun[i].transactionID2))
                                {
                                    LogDebug("STUN refused by ICMP remote \"" + stunHostnames[i] + "\"");
                                    pendingStun[i].dead = true;
                                    goto finish;
                                }
                            }
                        }
                    }

                    liveStunCount++;

finish:
                    // If all current STUNs have failed, start a fresh one:
                    if (liveStunCount == 0 && i == stunStartedCount - 1 && stunStartedCount < pendingStun.Length)
                    {
                        stunStartedCount++;
                    }
                }



                if (liveStunCount == 0 && stunStartedCount == pendingStun.Length)
                {
                    // We failed to get a response (NOTE: expiry time gets set when we _start_)
                    stunInProgress = false;
                }
            }

            if (!stunInProgress)
            {
                PostStunResults();
            }
        }
Example #24
0
        private void ConnectImpl(string host, int port, int timeout, Action <NetHandler, Exception> callback)
        {
            if (!running)
            {
                throw new ObjectDisposedException(ToString());
            }
            Stopwatch clock = new Stopwatch();

            clock.Start();
            Dns.BeginGetHostAddresses(host, ar =>
            {
                clock.Stop();
                timeout -= (int)clock.ElapsedMilliseconds;
                try
                {
                    IPAddress[] iplist = Dns.EndGetHostAddresses(ar);
                    if (timeout > 0)
                    {
                        AddressFamily family = AddressFamily.InterNetwork;
                        for (int i = 0; i < iplist.Length; ++i)
                        {
                            if (iplist[i].AddressFamily == AddressFamily.InterNetworkV6)
                            {
                                family = AddressFamily.InterNetworkV6;
                                break;
                            }
                        }
                        NetHandlerImpl socket = new NetHandlerImpl(family, this);
                        Timer timer           = new Timer(state =>
                        {
                            socket.Socket.Close();
                        }, null, Timeout.Infinite, Timeout.Infinite);
                        socket.Socket.BeginConnect(iplist, port, result =>
                        {
                            try
                            {
                                timer.Dispose();
                            }
                            catch
                            {
                            }
                            Exception exception = null;
                            try
                            {
                                socket.Socket.EndConnect(result);
                                socket.Socket.Blocking = false;
                                socket.OnConnected();
                            }
                            catch (ObjectDisposedException)
                            {
                                exception = new SocketException((int)SocketError.TimedOut);
                            }
                            catch (Exception e)
                            {
                                exception = e;
                                socket.Socket.Close();
                            }
                            callback(exception == null ? socket : null, exception);
                        }, null);
                        timer.Change(timeout, Timeout.Infinite);
                    }
                    else
                    {
                        callback(null, new SocketException((int)SocketError.TimedOut));
                    }
                }
                catch (Exception e)
                {
                    callback(null, e);
                }
            }, null);
        }
Example #25
0
 public void Dns_BeginGetHostAddresses_CallSocketInit_Ok()
 {
     NameResolutionPal.FakesReset();
     Assert.ThrowsAny <Exception>(() => Dns.BeginGetHostAddresses(null, null, null));
     Assert.NotEqual(0, NameResolutionPal.FakesEnsureSocketsAreInitializedCallCount);
 }
Example #26
0
        public override void Open(NpgsqlConnector context, Int32 timeout)
        {
            try
            {
                NpgsqlEventLog.LogMethodEnter(LogLevel.Debug, CLASSNAME, "Open");

                IAsyncResult result;
                // Keep track of time remaining; Even though there may be multiple timeout-able calls,
                // this allows us to still respect the caller's timeout expectation.
                DateTime attemptStart;

                attemptStart = DateTime.Now;

                result = Dns.BeginGetHostAddresses(context.Host, null, null);

                if (!result.AsyncWaitHandle.WaitOne(timeout, true))
                {
                    // Timeout was used up attempting the Dns lookup
                    throw new TimeoutException(resman.GetString("Exception_DnsLookupTimeout"));
                }

                timeout -= Convert.ToInt32((DateTime.Now - attemptStart).TotalMilliseconds);

                IPAddress[] ips    = Dns.EndGetHostAddresses(result);
                Socket      socket = null;
                Exception   lastSocketException = null;

                // try every ip address of the given hostname, use the first reachable one
                // make sure not to exceed the caller's timeout expectation by splitting the
                // time we have left between all the remaining ip's in the list.
                for (int i = 0; i < ips.Length; i++)
                {
                    NpgsqlEventLog.LogMsg(resman, "Log_ConnectingTo", LogLevel.Debug, ips[i]);

                    IPEndPoint ep = new IPEndPoint(ips[i], context.Port);
                    socket = new Socket(ep.AddressFamily, SocketType.Stream, ProtocolType.Tcp);

                    attemptStart = DateTime.Now;

                    try
                    {
                        result = socket.BeginConnect(ep, null, null);

                        if (!result.AsyncWaitHandle.WaitOne(timeout / (ips.Length - i), true))
                        {
                            throw new TimeoutException(resman.GetString("Exception_ConnectionTimeout"));
                        }

                        socket.EndConnect(result);

                        // connect was successful, leave the loop
                        break;
                    }
                    catch (Exception e)
                    {
                        NpgsqlEventLog.LogMsg(resman, "Log_FailedConnection", LogLevel.Normal, ips[i]);

                        timeout            -= Convert.ToInt32((DateTime.Now - attemptStart).TotalMilliseconds);
                        lastSocketException = e;

                        socket.Close();
                        socket = null;
                    }
                }

                if (socket == null)
                {
                    throw lastSocketException;
                }

                NpgsqlNetworkStream baseStream = new NpgsqlNetworkStream(socket, true);
                Stream sslStream = null;

                // If the PostgreSQL server has SSL connectors enabled Open SslClientStream if (response == 'S') {
                if (context.SSL || (context.SslMode == SslMode.Require) || (context.SslMode == SslMode.Prefer))
                {
                    baseStream
                    .WriteInt32(8)
                    .WriteInt32(80877103);

                    // Receive response
                    Char response = (Char)baseStream.ReadByte();

                    if (response == 'S')
                    {
                        //create empty collection
                        X509CertificateCollection clientCertificates = new X509CertificateCollection();

                        //trigger the callback to fetch some certificates
                        context.DefaultProvideClientCertificatesCallback(clientCertificates);

                        //if (context.UseMonoSsl)
                        if (!NpgsqlConnector.UseSslStream)
                        {
                            SslClientStream sslStreamPriv;

                            sslStreamPriv = new SslClientStream(
                                baseStream,
                                context.Host,
                                true,
                                SecurityProtocolType.Default,
                                clientCertificates);

                            sslStreamPriv.ClientCertSelectionDelegate =
                                new CertificateSelectionCallback(context.DefaultCertificateSelectionCallback);
                            sslStreamPriv.ServerCertValidationDelegate =
                                new CertificateValidationCallback(context.DefaultCertificateValidationCallback);
                            sslStreamPriv.PrivateKeyCertSelectionDelegate =
                                new PrivateKeySelectionCallback(context.DefaultPrivateKeySelectionCallback);
                            sslStream = sslStreamPriv;
                        }
                        else
                        {
                            SslStream sslStreamPriv;

                            sslStreamPriv = new SslStream(baseStream, true, context.DefaultValidateRemoteCertificateCallback);

                            sslStreamPriv.AuthenticateAsClient(context.Host, clientCertificates, System.Security.Authentication.SslProtocols.Default, false);
                            sslStream = sslStreamPriv;
                        }
                    }
                    else if (context.SslMode == SslMode.Require)
                    {
                        throw new InvalidOperationException(resman.GetString("Exception_Ssl_RequestError"));
                    }
                }

                context.Socket     = socket;
                context.BaseStream = baseStream;
                context.Stream     = new BufferedStream(sslStream == null ? baseStream : sslStream, 8192);

                NpgsqlEventLog.LogMsg(resman, "Log_ConnectedTo", LogLevel.Normal, context.Host, context.Port);
                ChangeState(context, NpgsqlConnectedState.Instance);
            }
            catch (Exception e)
            {
                throw new NpgsqlException(string.Format(resman.GetString("Exception_FailedConnection"), context.Host), e);
            }
        }
Example #27
0
 public static IPAddress QueryActiveIPAddress(int timeout = 300, string hostNameOrAddress = "www.baidu.com")
 {
     if (string.IsNullOrEmpty(hostNameOrAddress))
     {
         return(null);
     }
     using (AutoResetEvent events = new AutoResetEvent(false))
     {
         IPAddress address    = null;
         Stopwatch stopwatch  = new Stopwatch();
         bool      istimedout = false;
         try
         {
             Dns.BeginGetHostAddresses(hostNameOrAddress, (ar) =>
             {
                 if (istimedout)
                 {
                     return;
                 }
                 try
                 {
                     IPAddress[] addresses = Dns.EndGetHostAddresses(ar);
                     if (addresses != null && addresses.Length > 0)
                     {
                         foreach (IPAddress i in addresses)
                         {
                             if (i.AddressFamily == AddressFamily.InterNetwork)
                             {
                                 address = i;
                                 break;
                             }
                         }
                         events.Set();
                     }
                 }
                 catch (Exception)
                 {
                 }
             }, null);
         }
         catch (Exception)
         {
             return(null);
         }
         do
         {
             stopwatch.Start();
             if (!events.WaitOne(timeout))
             {
                 istimedout = true;
                 return(null);
             }
             else if (address == null)
             {
                 return(null);
             }
             stopwatch.Stop();
         } while (false);
         timeout -= Convert.ToInt32(stopwatch.ElapsedMilliseconds);
         if (timeout <= 0)
         {
             return(null);
         }
         using (Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
         {
             try
             {
                 socket.NoDelay = true;
                 socket.BeginConnect(new IPEndPoint(address, 443), (ar) =>
                 {
                     if (istimedout)
                     {
                         return;
                     }
                     try
                     {
                         socket.EndConnect(ar);
                         EndPoint localEP = socket.LocalEndPoint;
                         if (localEP != null)
                         {
                             IPEndPoint ipep = (IPEndPoint)localEP;
                             address         = ipep.Address;
                             events.Set();
                         }
                     }
                     catch (Exception)
                     {
                         address = null;
                     }
                 }, null);
             }
             catch (Exception)
             {
                 return(null);
             }
             do
             {
                 if (!events.WaitOne(timeout))
                 {
                     istimedout = true;
                     return(null);
                 }
             } while (false);
             MalockSocket.Close(socket);
         }
         return(address);
     }
 }