Ejemplo n.º 1
0
 public IEnumerable <IPAddress> GetLocalIpAddresses() => Dns.GetHostEntry(Dns.GetHostName()).AddressList;
 public SupervisorValueReadArrayTests(TestServerFixture server)
 {
     _server    = server;
     _hostEntry = Try.Op(() => Dns.GetHostEntry(Utils.GetHostName()))
                  ?? Try.Op(() => Dns.GetHostEntry("localhost"));
 }
Ejemplo n.º 3
0
        protected ServiceUpnp(Device aDevice, ServiceType aType, IProtocol aProtocol, IEventUpnpProvider aEventServer)
            : base(aDevice, aType, aProtocol)
        {
            Server = aEventServer;
            iMutex = new Mutex();
            iUnsubscribeCompleted = new ManualResetEvent(false);
            iControlUri           = new Uri(Location.Find(ServiceLocationUpnp.kKeyUpnpControlUri));
            iSubscribing          = false;
            iUnsubscribing        = false;
            iPendingSubscribe     = false;
            iPendingUnsubscribe   = false;
            iClosing = false;

            if (Server != null)
            {
                iEventUri = new Uri(Location.Find(ServiceLocationUpnp.kKeyUpnpSubscriptionUri));
                IPAddress address;
                if (IPAddress.TryParse(iEventUri.Host, out address))
                {
                    iEventEndpoint = new IPEndPoint(address, iEventUri.Port);
                }
                else
                {
                    try
                    {
                        IPAddress[] addresses = Dns.GetHostEntry(iEventUri.Host).AddressList;
                        for (int i = 0; i < addresses.Length && address == null; i++)
                        {
                            if (addresses[i].AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)
                            {
                                address = addresses[i];
                                break;
                            }
                        }
                        if (address != null)
                        {
                            iEventEndpoint = new IPEndPoint(address, iEventUri.Port);
                        }
                        else
                        {
                            UserLog.WriteLine("Endpoint not found: " + iEventUri.Host + ":" + iEventUri.Port);
                            throw new NetworkError();
                        }
                    }
                    catch (Exception ex)
                    {
                        throw (new ServiceException(903, "Endpoint lookup failure: " + iEventUri.Host + ":" + iEventUri.Port + ", " + ex));
                    }
                }

                iRequest           = new TcpClientStream();
                iWriteBuffer       = new Swb(kMaxWriteBufferBytes, iRequest);
                iReadBuffer        = new Srb(kMaxReadBufferBytes, iRequest);
                iWriter            = new WriterRequest(iWriteBuffer);
                iReader            = new ReaderResponse2(iReadBuffer);
                iHeaderUpnpSid     = new HeaderUpnpSid();
                iHeaderUpnpServer  = new HeaderUpnpServer();
                iHeaderUpnpTimeout = new HeaderUpnpTimeout();
                iReader.AddHeader(iHeaderUpnpSid);
                iReader.AddHeader(iHeaderUpnpServer);
                iReader.AddHeader(iHeaderUpnpTimeout);
            }
        }
        public List <IPAddress> getPossibleIpAddresses()
        {
            IPHostEntry ipHost = Dns.GetHostEntry(Dns.GetHostName());

            return(ipHost.AddressList.Where(ip => ip.AddressFamily == AddressFamily.InterNetwork).ToList());
        }
Ejemplo n.º 5
0
        private async Task RunAsync()
        {
            try
            {
                var address = BindingAddress.Parse(Options.Url);

                if (!IPAddress.TryParse(address.Host, out var ip))
                {
                    ip = Dns.GetHostEntry(address.Host).AddressList.First();
                }

                var endpoint = new IPEndPoint(ip, address.Port);

                _logger.LogInformation($"Connecting to '{endpoint}'.");

                await using var context = await _connectionFactory.ConnectAsync(endpoint);

                _logger.LogInformation($"Connected to '{endpoint}'.");

                var originalTransport     = context.Transport;
                IAsyncDisposable sslState = null;
                if (address.Scheme.Equals("https", StringComparison.OrdinalIgnoreCase))
                {
                    _logger.LogInformation("Starting TLS handshake.");

                    var memoryPool        = context.Features.Get <IMemoryPoolFeature>()?.MemoryPool;
                    var inputPipeOptions  = new StreamPipeReaderOptions(memoryPool, memoryPool.GetMinimumSegmentSize(), memoryPool.GetMinimumAllocSize(), leaveOpen: true);
                    var outputPipeOptions = new StreamPipeWriterOptions(pool: memoryPool, leaveOpen: true);

                    var sslDuplexPipe = new SslDuplexPipe(context.Transport, inputPipeOptions, outputPipeOptions);
                    var sslStream     = sslDuplexPipe.Stream;
                    sslState = sslDuplexPipe;

                    context.Transport = sslDuplexPipe;

                    await sslStream.AuthenticateAsClientAsync(new SslClientAuthenticationOptions
                    {
                        TargetHost = address.Host,
                        RemoteCertificateValidationCallback = (_, __, ___, ____) => true,
                        ApplicationProtocols = new List <SslApplicationProtocol> {
                            SslApplicationProtocol.Http2
                        },
                        EnabledSslProtocols = SslProtocols.Tls12,
                    }, CancellationToken.None);

                    _logger.LogInformation($"TLS handshake completed successfully.");
                }

                var http2Utilities = new Http2Utilities(context, _logger, _stopTokenSource.Token);

                try
                {
                    await Options.Scenaro(http2Utilities);
                }
                catch (Exception ex)
                {
                    _logger.LogError(ex, "App error");
                    throw;
                }
                finally
                {
                    // Unwind Https for shutdown. This must happen before context goes ot of scope or else DisposeAsync will hang
                    context.Transport = originalTransport;

                    if (sslState != null)
                    {
                        await sslState.DisposeAsync();
                    }
                }
            }
            finally
            {
                HostApplicationLifetime.StopApplication();
            }
        }
Ejemplo n.º 6
0
        private void ProcessSocket(Socket requestSocket)
        {
            using (requestSocket)
            {
                if (requestSocket.Connected)
                {
                    bool IsHttps = false;
                    GetMessageFromSocket(requestSocket, out byte[] httpByteArray);
                    string[] httpFields = SplitHttpToArray(httpByteArray);
                    string   hostField  = httpFields.FirstOrDefault(x => x.Contains("Host"));
                    if (hostField == null)
                    {
                        return;
                    }
                    int      UsedPort   = 0;
                    string[] hostFields = hostField.Split(' ');
                    string   host       = hostFields[1];
                    bool     isClosed   = IsBlocked(host);
                    try
                    {
                        if (host.IndexOf(':') != -1)
                        {
                            string[] trueports = host.Split(':');
                            portInt = int.Parse(trueports[1]);
                            IsHttps = true;
                        }

                        if (isClosed)
                        {
                            SendErrorPage(requestSocket, host);
                            Console.WriteLine(" {0} in black list.", host);
                            return;
                        }
                        else
                        {
                            if (IsHttps)
                            {
                                UsedPort = portInt;
                            }
                            else
                            {
                                UsedPort = sendPort;
                            }

                            Console.WriteLine("request to " + hostField + "|| port: " + UsedPort);
                            IPHostEntry ipHostEntry = Dns.GetHostEntry(host);


                            IPEndPoint ipEndPoint = new IPEndPoint(ipHostEntry.AddressList[0], UsedPort);
                            using (Socket replySocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
                            {
                                replySocket.Connect(ipEndPoint);
                                if (replySocket.Send(httpByteArray, httpByteArray.Length, SocketFlags.None) != httpByteArray.Length)
                                {
                                    Console.WriteLine("Can''t connect ");
                                }
                                else
                                {
                                    GetMessageFromSocket(replySocket, out byte[] httpResponse);
                                    requestSocket.Send(httpResponse, httpResponse.Length, SocketFlags.None);
                                    httpFields = SplitHttpToArray(httpResponse);

                                    string[] responseCode = httpFields[0].Split(' ');
                                    if (responseCode == null)
                                    {
                                        return;
                                    }
                                    Console.WriteLine("{0} answer code: {1}", hostField, responseCode[1]);
                                }
                            }
                        }
                        requestSocket.Close();
                    }
                    catch (Exception)
                    {
                        Console.WriteLine("Данный порт не поддерживается(порт: {0})", portInt);
                    }
                }
            }
        }
Ejemplo n.º 7
0
        // TODO: Might be moved and refactored when is needed for other tasks
        public static string GetBaseAddress(string networkHost, int?httpPort)
        {
            var port = httpPort ?? DefaultHttpPort;

            if (string.IsNullOrEmpty(networkHost))
            {
                return($"http://localhost:{port}/");
            }

            var host = networkHost;

            if (networkHost.IndexOf(',') >= 0)             // Uri host must not contain comma, but elasticsearch.yml supports it
            {
                var hosts = networkHost.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries).Select(h => h.Trim());
                host = hosts.FirstOrDefault(h => h == "localhost" || h == "127.0.0.1" ||
                                            h == LocalhostPlaceholder || h == LocalhostV4Placeholder || h == LocalhostV6Placeholder) // prefer local interface
                       ?? hosts.First();
            }

            switch (host)
            {
            case LocalhostPlaceholder:
                host = "localhost";
                break;

            case LocalhostV4Placeholder:
                host = "127.0.0.1";
                break;

            case LocalhostV6Placeholder:
                host = "[::1]";
                break;

            //TODO: differentiate between _site_ and _global_
            case SiteAddressPlaceholder:
            case GlobalAddressPlaceholder:
            case SiteAddressV4Placeholder:
            case GlobalAddressV4Placeholder:
            case SiteAddressV6Placeholder:
            case GlobalAddressV6Placeholder:
                IPHostEntry ipHostEntry = Dns.GetHostEntry(Dns.GetHostName());
                var         ipAddresses = ipHostEntry.AddressList
                                          .Where(a => !IPAddress.IsLoopback(a) && (a.AddressFamily == AddressFamily.InterNetwork || a.AddressFamily == AddressFamily.InterNetworkV6));
                if (host == SiteAddressV4Placeholder || host == GlobalAddressV4Placeholder)
                {
                    ipAddresses = ipAddresses.Where(a => a.AddressFamily == AddressFamily.InterNetwork);
                }
                if (host == SiteAddressV6Placeholder || host == GlobalAddressV6Placeholder)
                {
                    ipAddresses = ipAddresses.Where(a => a.AddressFamily == AddressFamily.InterNetworkV6);
                }
                var ipAddress = ipAddresses.First();
                host = ipAddress.AddressFamily == AddressFamily.InterNetworkV6 ? $"[{ipAddress}]" : ipAddress.ToString();
                break;
            }

            // do not remove trailing slash. Base address *must* have it
            var baseAddress = $"http://{host}:{port}/";

            if (!Uri.IsWellFormedUriString(baseAddress, UriKind.Absolute))
            {
                // uri is not right, as installation is always local it's better to try localhost anyway
                baseAddress = $"http://localhost:{port}/";
            }

            return(baseAddress);
        }
        /// <summary>
        /// Get all local ip addresses (non alloc version)
        /// </summary>
        /// <param name="targetList">result list</param>
        /// <param name="addrType">type of address (IPv4, IPv6 or both)</param>
        public static void GetLocalIpList(List <string> targetList, LocalAddrType addrType)
        {
            bool ipv4 = (addrType & LocalAddrType.IPv4) == LocalAddrType.IPv4;
            bool ipv6 = (addrType & LocalAddrType.IPv6) == LocalAddrType.IPv6;

#if WINRT && !UNITY_EDITOR
            foreach (HostName localHostName in NetworkInformation.GetHostNames())
            {
                if (localHostName.IPInformation != null &&
                    ((ipv4 && localHostName.Type == HostNameType.Ipv4) ||
                     (ipv6 && localHostName.Type == HostNameType.Ipv6)))
                {
                    targetList.Add(localHostName.ToString());
                }
            }
#else
            try
            {
                foreach (NetworkInterface ni in NetworkInterface.GetAllNetworkInterfaces())
                {
                    //Skip loopback and disabled network interfaces
                    if (ni.NetworkInterfaceType == NetworkInterfaceType.Loopback ||
                        ni.OperationalStatus != OperationalStatus.Up)
                    {
                        continue;
                    }

                    var ipProps = ni.GetIPProperties();

                    //Skip address without gateway
                    if (ipProps.GatewayAddresses.Count == 0)
                    {
                        continue;
                    }

                    foreach (UnicastIPAddressInformation ip in ipProps.UnicastAddresses)
                    {
                        var address = ip.Address;
                        if ((ipv4 && address.AddressFamily == AddressFamily.InterNetwork) ||
                            (ipv6 && address.AddressFamily == AddressFamily.InterNetworkV6))
                        {
                            targetList.Add(address.ToString());
                        }
                    }
                }
            }
            catch
            {
                //ignored
            }

            //Fallback mode (unity android)
            if (targetList.Count == 0)
            {
#if NETCORE
                var hostTask = Dns.GetHostEntryAsync(Dns.GetHostName());
                hostTask.Wait();
                var host = hostTask.Result;
#else
                var host = Dns.GetHostEntry(Dns.GetHostName());
#endif
                foreach (IPAddress ip in host.AddressList)
                {
                    if ((ipv4 && ip.AddressFamily == AddressFamily.InterNetwork) ||
                        (ipv6 && ip.AddressFamily == AddressFamily.InterNetworkV6))
                    {
                        targetList.Add(ip.ToString());
                    }
                }
            }
#endif
            if (targetList.Count == 0)
            {
                if (ipv4)
                {
                    targetList.Add("127.0.0.1");
                }
                if (ipv6)
                {
                    targetList.Add("::1");
                }
            }
        }
Ejemplo n.º 9
0
        /// <summary>
        /// Creates a new <see cref="ClientConnection"/> instance.
        /// </summary>
        /// <param name="parent">Parent data publisher.</param>
        /// <param name="clientID">Client ID of associated connection.</param>
        /// <param name="commandChannel"><see cref="TcpServer"/> command channel used to lookup connection information.</param>
        public ClientConnection(DataPublisher parent, Guid clientID, TcpServer commandChannel)
        {
            m_parent         = parent;
            m_clientID       = clientID;
            m_commandChannel = commandChannel;
            m_subscriberID   = clientID;
            m_keyIVs         = null;
            m_cipherIndex    = 0;

            // Setup ping timer
            m_pingTimer           = new System.Timers.Timer();
            m_pingTimer.Interval  = 5000.0D;
            m_pingTimer.AutoReset = true;
            m_pingTimer.Elapsed  += m_pingTimer_Elapsed;
            m_pingTimer.Start();

            // Setup reconnect timer
            m_reconnectTimer           = new System.Timers.Timer();
            m_reconnectTimer.Interval  = 1000.0D;
            m_reconnectTimer.AutoReset = false;
            m_reconnectTimer.Elapsed  += m_reconnectTimer_Elapsed;

            // Attempt to lookup remote connection identification for logging purposes
            try
            {
                TransportProvider <Socket> client;
                IPEndPoint remoteEndPoint = null;

                if ((object)commandChannel != null && commandChannel.TryGetClient(clientID, out client))
                {
                    remoteEndPoint = client.Provider.RemoteEndPoint as IPEndPoint;
                }

                if ((object)remoteEndPoint != null)
                {
                    m_ipAddress = remoteEndPoint.Address;

                    if (remoteEndPoint.AddressFamily == AddressFamily.InterNetworkV6)
                    {
                        m_connectionID = "[" + m_ipAddress + "]:" + remoteEndPoint.Port;
                    }
                    else
                    {
                        m_connectionID = m_ipAddress + ":" + remoteEndPoint.Port;
                    }

                    try
                    {
                        IPHostEntry ipHost = Dns.GetHostEntry(remoteEndPoint.Address);

                        if (!ipHost.HostName.IsNullOrWhiteSpace())
                        {
                            m_hostName     = ipHost.HostName;
                            m_connectionID = m_hostName + " (" + m_connectionID + ")";
                        }
                    }
                    catch
                    {
                        // Just ignoring possible DNS lookup failures...
                    }
                }
            }
            catch
            {
                // At worst we'll just use the client GUID for identification
                m_connectionID = (m_subscriberID == Guid.Empty ? clientID.ToString() : m_subscriberID.ToString());
            }

            if (m_connectionID.IsNullOrWhiteSpace())
            {
                m_connectionID = "unavailable";
            }

            if (m_hostName.IsNullOrWhiteSpace())
            {
                if (m_ipAddress != null)
                {
                    m_hostName = m_ipAddress.ToString();
                }
                else
                {
                    m_hostName = m_connectionID;
                }
            }

            if (m_ipAddress == null)
            {
                m_ipAddress = System.Net.IPAddress.None;
            }
        }
Ejemplo n.º 10
0
        // Установить сервер
        private void serverButton_Click(object sender, EventArgs e)
        {
            try
            {
                textBoxNetInfo.Text = "";
                m_ClientReady       = m_ServerReady = false;
                ChannelServices.RegisterChannel(new TcpChannel(8080), false);

                m_FromClient    = new FromClientTransmittor();
                m_RefFromClient = RemotingServices.Marshal(m_FromClient, "FromClientTransmittor");

                // Обработка события на запрос о ничьей
                m_FromClient.ToServerRemiEvent += ToServerRemiEvent;

                // Обработка события на сообщение о начале игры
                m_FromClient.StartGameEvent += StartGameEvent;

                // Обработка нового хода клиента
                m_FromClient.ToServerStepEvent += ToServerStepEvent;

                // Обработка события на сообщение о ничьей
                m_FromClient.ToServerDeliverEvent += ToServerDeliverEvent;

                // Обработка события на готовность клиента играть
                m_FromClient.ToServerReadyEvent += ToServerReadyEvent;

                // Обработка события на отключение клиента
                m_FromClient.ToServerDisableEvent += ToServerDisableEvent;

                m_WhoStep    = ObjectType.Cross;
                m_TypePlayer = TypePlayer.Server;
                IPAddress ip = Dns.GetHostEntry(Dns.GetHostName()).AddressList[Dns.GetHostEntry(Dns.GetHostName()).AddressList.Length - 1];
                textBoxNetInfo.Text += "Сервер установлен\r\nIP-адрес: " + ip + "\r\n";
                textBoxNetInfo.Text += "Ожидаем подсоединения клиента\r\n";

                serverButton.Visible     = connectButton.Visible = startGameButton.Enabled = false;
                disconnectButton.Visible = true;
            }
            catch
            {
                MessageBox.Show("Сервер не установлен.", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
                try
                {
                    ChannelServices.UnregisterChannel(ChannelServices.RegisteredChannels[0]);
                }
// ReSharper disable EmptyGeneralCatchClause
                catch { }
// ReSharper restore EmptyGeneralCatchClause

                try
                {
                    if (m_RefFromClient != null)
                    {
                        RemotingServices.Unmarshal(m_RefFromClient);
                        RemotingServices.Disconnect(m_FromClient);
                    }
                }
// ReSharper disable EmptyGeneralCatchClause
                catch { }
// ReSharper restore EmptyGeneralCatchClause

                try
                {
                    if (m_RefFromServer != null)
                    {
                        RemotingServices.Unmarshal(m_RefFromServer);
                        RemotingServices.Disconnect(m_FromServer);
                    }
                }
// ReSharper disable EmptyGeneralCatchClause
                catch { }
// ReSharper restore EmptyGeneralCatchClause
            }
        }
Ejemplo n.º 11
0
        // Подключиться к серверу
        private void connectButton_Click(object sender, EventArgs e)
        {
            try
            {
                m_ClientReady = m_ServerReady = false;
                new ServerConnectForm(this).ShowDialog();
                if (IpConnect != "")
                {
                    ChannelServices.RegisterChannel(new TcpChannel(8081), false);

                    m_FromClient = (FromClientTransmittor)Activator.GetObject(typeof(FromClientTransmittor), "tcp://" + IpConnect + ":8080/FromClientTransmittor");

                    // Установить свой сервер для получения ответа от сервера
                    m_FromServer    = new FromServerTransmittor();
                    m_RefFromServer = RemotingServices.Marshal(m_FromServer, "FromServerTransmittor");

                    // Обработка события на запрос о ничьей
                    m_FromServer.ToClientRemiEvent += ToClientRemiEvent;

                    // Обработка события на сообщение о сдаче сервера
                    m_FromServer.ToClientDeliverEvent += ToClientDeliverEvent;

                    // Обработка очередного хода сервера
                    m_FromServer.ToClientStepEvent += ToClientStepEvent;

                    // Обработка события на готовность клиента играть
                    m_FromServer.ToClientReadyEvent += ToClientReadyEvent;

                    // Обработка события на отключение клиента
                    m_FromServer.ToClientDisableEvent += ToClientDisableEvent;

                    // Получение сетевого адреса клиента (вида tcp://xxx.xxx.xxx.xxx:8081)
                    IPAddress ip   = Dns.GetHostEntry(Dns.GetHostName()).AddressList[Dns.GetHostEntry(Dns.GetHostName()).AddressList.Length - 1];
                    string    addr = "tcp://" + ip + ":8081";

                    var cb = new AsyncCallback(StartGameQuery);
                    var d  = new StartGameDelegate(m_FromClient.StartGame);
                    d.BeginInvoke(addr, cb, null);

                    m_WhoStep                = ObjectType.Cross;
                    m_TypePlayer             = TypePlayer.Client;
                    serverButton.Visible     = connectButton.Visible = false;
                    disconnectButton.Visible = true;
                    textBoxNetInfo.Text      = "Соединение с сервером установлено\r\n";
                }
            }
            catch
            {
                MessageBox.Show("Подключение к серверу не установлено.", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
                ChannelServices.UnregisterChannel(ChannelServices.RegisteredChannels[0]);
                try
                {
                    if (m_RefFromClient != null)
                    {
                        RemotingServices.Unmarshal(m_RefFromClient);
                        RemotingServices.Disconnect(m_FromClient);
                    }
                }
// ReSharper disable EmptyGeneralCatchClause
                catch { }
// ReSharper restore EmptyGeneralCatchClause

                try
                {
                    if (m_RefFromServer != null)
                    {
                        RemotingServices.Unmarshal(m_RefFromServer);
                        RemotingServices.Disconnect(m_FromServer);
                    }
                }
// ReSharper disable EmptyGeneralCatchClause
                catch { }
// ReSharper restore EmptyGeneralCatchClause
            }
        }
Ejemplo n.º 12
0
        public List <DeviceModel> ScanVulnerabilities(List <Host> devices)
        {
            RestClient  restClient  = new RestClient("https://exploits.shodan.io/");
            RestRequest restRequest = new RestRequest("api/search", Method.GET);

            restRequest.AddParameter("key", _APIKEY);

            var vulnerableDevices = new List <DeviceModel>();

            foreach (var device in devices)
            {
                var vulnerabilities = new List <VulnerabilityModel>();
                var openPorts       = new List <int>();

                foreach (var port in device.Ports.Where(p => p.Service.Product != null))
                {
                    var product = "";
                    var version = "";
                    openPorts.Add(port.PortNumber);

                    if (port.Service.Version == null || port.Service.Product == null)
                    {
                        continue;
                    }

                    if (port.Service.Product != null)
                    {
                        if (port.Service.Product.Contains(" "))
                        {
                            product = port.Service.Product.Substring(0,
                                                                     port.Service.Product.IndexOf(" ", StringComparison.Ordinal) + 1);
                        }
                        else
                        {
                            product = port.Service.Product;
                        }
                    }

                    if (port.Service.Version != null)
                    {
                        if (port.Service.Version.Contains(" "))
                        {
                            version = port.Service.Version.Substring(0,
                                                                     port.Service.Version.IndexOf(" ", StringComparison.Ordinal) + 1);
                        }
                        else
                        {
                            version = port.Service.Version;
                        }

                        int index = -1;

                        for (int i = 0; i < 3; i++)
                        {
                            index = version.IndexOf(".", index + 1, StringComparison.Ordinal);

                            if (index == -1)
                            {
                                break;
                            }
                        }

                        if (index > 3)
                        {
                            version = version.Substring(0, index);
                        }
                    }

                    var searchTerm = $"{product} {version}";
                    restRequest.AddParameter("query", searchTerm);

                    // Limited to 1 request per second with Shodan, in case a request returns no results we'll wait 1 second before the next.
                    Thread.Sleep(1000);

                    var     query = restClient.Execute((IRestRequest)restRequest);
                    JObject parsedQuery;

                    try
                    {
                        parsedQuery = JObject.Parse(query.Content);
                        var array = parsedQuery.GetValue("matches");

                        foreach (var jObject in array)
                        {
                            var vulnerability = new VulnerabilityModel();

                            vulnerability.Port    = port.PortNumber;
                            vulnerability.Service =
                                $"{port.Service.Name} ({port.Service.Product})";
                            vulnerability.Version = port.Service.Version;
                            if (jObject["source"] != null)
                            {
                                vulnerability.Source = jObject["source"].ToString();
                            }
                            if (jObject["type"] != null)
                            {
                                vulnerability.Type = jObject["type"].ToString();
                            }
                            if (jObject["cve"] != null && jObject["cve"].HasValues)
                            {
                                vulnerability.CVE = jObject["cve"].ToObject <string[]>()[0];
                            }
                            if (jObject["date"] != null)
                            {
                                vulnerability.Date = DateTime.Parse(jObject["date"].ToString());
                            }

                            if (jObject["description"] != null)
                            {
                                var description = jObject["description"].ToString();
                                if (description.Length > 100)
                                {
                                    //Truncate long descriptions to display to users.
                                    var tempString = description.Substring(0, 100);
                                    if (tempString.LastIndexOf(' ') > 0)
                                    {
                                        description = tempString.Substring(0, tempString.LastIndexOf(' ')) + " ...";
                                    }
                                }

                                vulnerability.Description = description;
                            }

                            vulnerabilities.Add(vulnerability);
                        }
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine($"There was an error during the search.");
                    }
                }

                if (vulnerabilities.Any())
                {
                    var vulnerableDevice = new DeviceModel();
                    vulnerableDevice.OpenPorts       = openPorts;
                    vulnerableDevice.IP              = device.Address.ToString();
                    vulnerableDevice.PhysicalAddress = device.PhysicalAddress;
                    vulnerableDevice.Vendor          = device.Vendor;

                    try
                    {
                        vulnerableDevice.Hostname = Dns.GetHostEntry(device.Address).HostName;
                    }
                    catch (Exception e)
                    {
                        //GetHostEntry throws an exception if host not found.
                        vulnerableDevice.Hostname = "Hostname not found.";
                    }

                    // Remove duplicate instances of vulnerabilities by CVE
                    var vulnerabilitiesTest = DistinctByExtension.DistinctBy(vulnerabilities, x => x.CVE).ToList();

                    //Only keep top 5 most recent vulnerabilities

                    /*vulnerabilities = vulnerabilities.Where(x => x.Date.HasValue)
                     *  .OrderByDescending(x => x.Date.Value)
                     *  .Take(5).ToList();*/

                    vulnerableDevice.Vulnerabilities = vulnerabilities;

                    vulnerableDevices.Add(vulnerableDevice);

                    Console.WriteLine($"Vulnerability scan completed for {device.Address}. {vulnerableDevice.Vulnerabilities.Count} vulnerabilities found.");
                }
            }

            return(vulnerableDevices);
        }
Ejemplo n.º 13
0
        /// <summary>
        /// 启动
        /// </summary>
        private void Run(IServiceProvider component)
        {
            if (isDisposed == true)
            {
                throw new ObjectDisposedException("ZYServer is Disposed");
            }

            var config = component.GetRequiredService<SocketServerOptions>();


            IPEndPoint myEnd = new IPEndPoint(IPAddress.Any, Port);

            if (Host.Equals("ipv6any", StringComparison.CurrentCultureIgnoreCase))
            {
                myEnd = new IPEndPoint(IPAddress.IPv6Any, Port);
            }
            else if (!Host.Equals("any", StringComparison.CurrentCultureIgnoreCase))
            {
                if (String.IsNullOrEmpty(Host))
                {

                    IPHostEntry p = Dns.GetHostEntry(Dns.GetHostName());

                    foreach (IPAddress s in p.AddressList)
                    {
                        if (!s.IsIPv6LinkLocal && s.AddressFamily != AddressFamily.InterNetworkV6)
                        {
                            myEnd = new IPEndPoint(s, Port);
                            break;
                        }
                    }

                }
                else
                {
                    try
                    {
                        myEnd = new IPEndPoint(IPAddress.Parse(Host), Port);
                    }
                    catch (FormatException)
                    {

                        IPHostEntry p = Dns.GetHostEntry(Dns.GetHostName());

                        foreach (IPAddress s in p.AddressList)
                        {
                            if (!s.IsIPv6LinkLocal)
                                myEnd = new IPEndPoint(s, Port);
                        }
                    }

                }


            }

            sock = new Socket(myEnd.AddressFamily, SocketType.Stream, ProtocolType.Tcp);

            sock.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, 1);


            sock.Bind(myEnd);
            sock.Listen(config.BackLog);

            if(config.ReceiveTimeout>0)
                ReceiveTimeout = config.ReceiveTimeout;
            if (config.SendTimeout > 0)
                SendTimeout = config.SendTimeout;




            var memoryPool = component.GetRequiredService<MemoryPool<byte>>();
            var encode = component.GetRequiredService<Encoding>();
            var objFormat = component.GetRequiredService<ISerialization>();

            for (int i = 0; i < MaxConnectCout; i++)
            {
              
                var poolSend = component.GetRequiredService<ISend>();
                var poolAsyncSend = component.GetRequiredService<IAsyncSend>();

                ZYSocketAsyncEventArgs socketasyn = new ZYSocketAsyncEventArgs(
                    new LinesReadStream(MaxBufferSize),
                    new BufferWriteStream(memoryPool, poolSend, poolAsyncSend),
                    poolSend,
                    poolAsyncSend,
                    memoryPool,
                    encode,
                    objFormat,
                    config.IsLittleEndian
                   );
               
                poolSend.SetAccpet(socketasyn);
                poolAsyncSend.SetAccpet(socketasyn);

                socketasyn.Completed += new EventHandler<ZYSocketAsyncEventArgs>(Asyn_Completed);
                Accept(socketasyn);
            }

        }
Ejemplo n.º 14
0
        /// <summary>
        /// 启动
        /// </summary>
        private void Run()
        {
            if (isDisposed == true)
            {
                throw new ObjectDisposedException("ZYServer is Disposed");
            }


            IPEndPoint myEnd = new IPEndPoint(IPAddress.Any, Port);

            if (Host.Equals("ipv6any", StringComparison.CurrentCultureIgnoreCase))
            {
                myEnd = new IPEndPoint(IPAddress.IPv6Any, Port);
            }
            else if (!Host.Equals("any",StringComparison.CurrentCultureIgnoreCase))
            {
                if (String.IsNullOrEmpty(Host))
                {

                    IPHostEntry p = Dns.GetHostEntry(Dns.GetHostName());

                    foreach (IPAddress s in p.AddressList)
                    {
                        if (!s.IsIPv6LinkLocal && s.AddressFamily != AddressFamily.InterNetworkV6)
                        {
                            myEnd = new IPEndPoint(s, Port);
                            break;
                        }
                    }
                  
                }
                else
                {
                    try
                    {
                        myEnd = new IPEndPoint(IPAddress.Parse(Host), Port);
                    }
                    catch (FormatException)
                    {

                        IPHostEntry p = Dns.GetHostEntry(Dns.GetHostName());

                        foreach (IPAddress s in p.AddressList)
                        {
                            if (!s.IsIPv6LinkLocal)
                                myEnd = new IPEndPoint(s, Port);
                        }
                    }

                }           
            
            }

            sock = new Socket(myEnd.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
            sock.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, 1);

            sock.Bind(myEnd);
            sock.Listen(512);           
            ReceiveTimeout = 1000;

            var memoryPool = new Thruster.FastMemoryPool<byte>();

            for (int i = 0; i < MaxConnectCout; i++)
            {

                var netSend = new NetSend(true);

                ZYSocketAsyncEventArgs socketasyn = new ZYSocketAsyncEventArgs(
                    new LinesReadStream(MaxBufferSize),
                    new BufferWriteStream(memoryPool, netSend, netSend),
                    netSend,
                    netSend,
                    memoryPool,
                    Encoding.UTF8
                   );
               
                netSend.SetAccpet(socketasyn);
                socketasyn.Completed += new EventHandler<ZYSocketAsyncEventArgs>(Asyn_Completed);
                Accept(socketasyn);
            }


        }
Ejemplo n.º 15
0
        public ResponseAPI Execute(HttpContext context, dynamic dataReq = null)
        {
            ResponseAPI res = new ResponseAPI();

            StringValues HToken;

            context.Request.Headers.TryGetValue("Token", out HToken);
            Token = HToken.ToString();

            DateTime StartTime     = DateTime.Now;
            string   StackTraceMsg = string.Empty;

            try
            {
                StringValues HAccessToken;
                context.Request.Headers.TryGetValue("AccessToken", out HAccessToken);
                AccessToken = HAccessToken.ToString();

                IPHostEntry heserver = Dns.GetHostEntry(Dns.GetHostName());
                IPAddress = /*string.Join(',', heserver.AddressList.Select(x => x.ToString()).ToList());*/ context.Connection.RemoteIpAddress.ToString();

                StringValues HUserAgent;
                context.Request.Headers.TryGetValue("User-Agent", out HUserAgent);
                UserAgent = HUserAgent.ToString();

                StringValues HRecaptchaResponse;
                context.Request.Headers.TryGetValue("RecaptchaResponse", out HRecaptchaResponse);
                RecaptchaResponse = HRecaptchaResponse.ToString();

                // if (!this.GetType().Name.Equals("OauthAccessTokenGet")) this.ValidatePermission();

                /*
                 *   StringValues Husercode;
                 *   context.Request.Headers.TryGetValue("UserCode", out Husercode);
                 *   UserCode = Husercode.ToString();
                 */

                if (dataReq != null)
                {
                    try
                    {
                        dataReq = this.MappingRequest(dataReq);
                    }
                    catch (Exception)
                    {
                        dataReq = this.MappingRequestArr(dataReq);
                    }
                }

                this.ExecuteChild(dataReq, res);

                res.code    = "S0001";
                res.message = "SUCCESS";
                res.status  = "S";
            }
            catch (Exception ex)
            {
                StackTraceMsg = ex.StackTrace;
                //map error code, message
                ErrorCode error = EnumUtil.GetEnum <ErrorCode>(ex.Message);
                res.code = error.ToString();
                if (res.code == ErrorCode.U000.ToString())
                {
                    res.message = ex.Message;
                }
                else
                {
                    res.message = error.GetDescription();
                }

                res.status = "F";
            }
            finally
            {
                ASSETKKF_ADO.Mssql.Mcis.muAPILogAdo.GetInstant().Insert(new ASSETKKF_MODEL.Data.Mssql.Mcis.muAPILog()
                {
                    Token   = Token,
                    APIName = this.GetType().Name,
                    //RefID = this.Logger.RefID,
                    ServerName    = Environment.MachineName,
                    StartDate     = StartTime,
                    EndDate       = DateTime.Now,
                    Status        = res.status,
                    StatusMessage = res.message,
                    Input         = this.GetType().Name.Equals("OauthLogin") ? "" : JsonConvert.SerializeObject(dataReq),
                    Output        = JsonConvert.SerializeObject(res),
                    Remark        = StackTraceMsg
                });
            }
            return(res);
        }
Ejemplo n.º 16
0
        public static int Run(string[] args)
        {
            try
            {
                if (!HandleArguments(ref args))
                {
                    return(0);
                }
            }
            catch (OptionException e)
            {
                Console.Error.WriteLine(e.Message);
                return(1);
            }

            AppDomain.CurrentDomain.ProcessExit += ProcessExit;
            Console.CancelKeyPress += CancelKeyPress;
            ConsoleUtility.AddConsoleEventHandler(ConsoleEvent);

            Log.Level           = Configuration.LogLevel;
            Log.TimestampFormat = Configuration.LogTimestampFormat;

            foreach (var src in Configuration.DiscardLogSources)
            {
                Log.DiscardSources.Add(src);
            }

            if (Configuration.Loggers.Contains(ConsoleLogger.Name))
            {
                Log.Loggers.Add(new ConsoleLogger(
                                    Configuration.EnableColors, Configuration.ErrorColor,
                                    Configuration.WarningColor, Configuration.BasicColor,
                                    Configuration.InfoColor, Configuration.DebugColor));
            }

            if (Configuration.Loggers.Contains(FileLogger.Name))
            {
                Log.Loggers.Add(new FileLogger(
                                    Configuration.LogDirectory, Configuration.LogFileNameFormat));
            }

            if (!Debugger.IsAttached)
            {
                AppDomain.CurrentDomain.UnhandledException += UnhandledException;
            }

            _log.Basic("Starting {0}...", Name);

            var hosts = Configuration.AdjustHostsFile ?
                        new HostsFileManager() : null;
            var shell = Configuration.AdjustNetworkShell ?
                        new NetworkShellManager() : null;

            try
            {
                var region     = Configuration.Region;
                var slsHost    = ServerListParameters.GetUri(region).Host;
                var slsAddress = Configuration.ServerListAddress;

                hosts?.RemoveEntry(slsHost, slsAddress);

                var real = Dns.GetHostEntry(slsHost).AddressList[0];

                hosts?.AddEntry(slsHost, slsAddress);

                var slsHttps  = new IPEndPoint(slsAddress, 443);
                var realHttps = new IPEndPoint(real, slsHttps.Port);

                shell?.RemovePortProxy(slsHttps, realHttps);
                shell?.AddPortProxy(slsHttps, realHttps);

                var slsPort   = Configuration.ServerListPort;
                var slsParams = new ServerListParameters(real,
                                                         Configuration.ServerListAddress,
                                                         slsPort != 0 ? (int?)slsPort : null,
                                                         Configuration.GameAddress, Configuration.GameBasePort,
                                                         region, Configuration.ServerListTimeout,
                                                         Configuration.ServerListRetries);

                using (var slsProxy = new ServerListProxy(slsParams))
                {
                    if (Configuration.EnableServerList)
                    {
                        slsProxy.Start();
                    }

                    var pool = new ObjectPool <SocketAsyncEventArgs>(
                        () => new SocketAsyncEventArgs(), x => x.Reset(),
                        Configuration.PoolLimit != 0 ? (int?)Configuration.PoolLimit : null);
                    var proc = new PacketProcessor(new CompilerPacketSerializer(
                                                       new MessageTables(region, OpCodeTable.Versions[region])));
                    var proxies = slsProxy.Servers.Select(x => new GameProxy(x,
                                                                             pool, proc, Configuration.GameBacklog,
                                                                             Configuration.GameTimeout)
                    {
                        MaxClients = Configuration.GameMaxClients
                    }).ToArray();

                    foreach (var proxy in proxies)
                    {
                        proxy.Start();
                    }

                    var loader = new PluginLoader(Configuration.PluginDirectory,
                                                  Configuration.PluginPattern, Configuration.DisablePlugins);

                    loader.Start(proxies);

                    _log.Basic("{0} started", Name);

                    _runningEvent.Wait();

                    _log.Basic("{0} shutting down...", Name);

                    loader.Stop(proxies);

                    foreach (var proxy in proxies)
                    {
                        proxy.Dispose();
                    }
                }
            }
            finally
            {
                hosts?.Dispose();
                shell?.Dispose();
            }

            _exitEvent.Set();

            return(0);
        }
Ejemplo n.º 17
0
 private static IPAddress[] GetIps(string host)
 {
     return(Dns.GetHostEntry(host).AddressList);
 }
Ejemplo n.º 18
0
        public bool BindSocket()
        {
            try
            {
                IPHostEntry ipHostInfo = Dns.GetHostEntry(Dns.GetHostName());
                IPAddress   ipAddress  = ipHostInfo.AddressList[0];
                //IPEndPoint localEndPoint = new IPEndPoint(ipAddress, _protocolPort); // Get from hostname
                IPEndPoint localEndPoint = new IPEndPoint(IPAddress.Parse("172.16.21.50"), _protocolPort); // Static


                Socket listener = new Socket(
                    ipAddress.AddressFamily,
                    SocketType.Stream,
                    ProtocolType.Tcp);
                try
                {
                    listener.Bind(localEndPoint);
                }
                catch (ArgumentNullException argNullE)
                {
                    //Console.WriteLine($"Socket Listener Connect Exception : LocalEndPoint was null.");
                    throw argNullE;
                }
                catch (SocketException socE)
                {
                    throw socE;
                    //Console.WriteLine($"Socket Listener Connect Exception : An error occurred when attempting to access the socket.");
                }
                catch (ObjectDisposedException objDisE)
                {
                    throw objDisE;
                    //Console.WriteLine($"Socket Listener Connect Exception : Socket has been closed.");
                }
                catch (SecurityException secE)
                {
                    throw secE;
                    //Console.WriteLine($"Socket Listener Connect Exception : A caller higher in the call stack does not have permission for the requested operation.");
                }
                catch (Exception e)
                {
                    //Console.WriteLine($"Socket Listener Connect Exception : Something blocked the socket bind.");
                    return(false);

                    throw e;
                }

                try
                {
                    listener.Listen(10);
                }
                catch (SocketException socE)
                {
                    throw socE;
                    //Console.WriteLine($"Socket Listener Connect Exception : An error occurred when attempting to access the socket.");
                }
                catch (ObjectDisposedException objDisE)
                {
                    throw objDisE;
                    //Console.WriteLine($"Socket Listener Connect Exception : Socket has been closed.");
                }
                catch (Exception e)
                {
                    //Console.WriteLine($"Socket Listener Connect Exception");
                    return(false);

                    throw e;
                }

                _socket = listener;

                return(true);
            }
            catch (Exception e)
            {
                //Console.WriteLine($"Socket Listener Connect Exception : Something went completely wrong.");
                return(false);

                throw e;
            }
        }
Ejemplo n.º 19
0
 public static IPHostEntry GetHostEntry()
 {
     return(Dns.GetHostEntry(Dns.GetHostName()));
 }
Ejemplo n.º 20
0
    // This method sets up a socket for receiving messages from the Network
    private async void ReceiveMulticast()
    {
        // Data buffer for incoming data.
        byte[] bytes = new Byte[1024];

        // Determine the IP address of localhost
        IPHostEntry ipHostInfo = Dns.GetHostEntry(Dns.GetHostName());
        IPAddress   ipAddress  = null;

        foreach (IPAddress ip in ipHostInfo.AddressList)
        {
            if (ip.AddressFamily == AddressFamily.InterNetwork)
            {
                ipAddress = ip;
                break;
            }
        }

        IPEndPoint localEndPoint = new IPEndPoint(ipAddress, myPort);

        // Create a TCP/IP socket for receiving message from the Network.
        TcpListener listener = new TcpListener(localEndPoint);

        listener.Start(88);

        try
        {
            string data = null;

            // Start listening for connections.
            while (true)
            {
                //Console.WriteLine("Waiting for a connection...");

                // Program is suspended while waiting for an incoming connection.
                TcpClient tcpClient = await listener.AcceptTcpClientAsync();

                //Console.WriteLine("connectted");
                data = null;

                // Receive one message from the network
                while (true)
                {
                    bytes = new byte[1024];
                    NetworkStream readStream = tcpClient.GetStream();
                    int           bytesRec   = await readStream.ReadAsync(bytes, 0, 1024);

                    data += Encoding.ASCII.GetString(bytes, 0, bytesRec);

                    // All messages ends with "<EOM>"
                    // Check whether a complete message has been received
                    if (data.IndexOf("<EOM>") > -1)
                    {
                        break;
                    }
                }
                //***** the data is received, select the type of the data.
                char preamble = data[0];
                switch (preamble)
                {
                case 'M':
                    // a typical message is like: "Msg #3 from Middleware3:[7]<EOM>\n"

                    // retrive sender id and such
                    string keyword             = "Middleware";
                    int    senderPositionInMsg = data.IndexOf(keyword) + keyword.Length;
                    int    columPosition       = data.IndexOf(":");
                    string senderStr           = data.Substring(senderPositionInMsg, columPosition - senderPositionInMsg);


                    int    AtPosition   = data.IndexOf("[");
                    int    EndPosition  = data.IndexOf("]");
                    int    hashPosition = data.IndexOf("#");
                    int    fromPosition = data.IndexOf("from");
                    string restOfString = data.Substring(hashPosition + 1, fromPosition - hashPosition - 1);

                    string MsgStamp    = data.Substring(AtPosition + 1, EndPosition - AtPosition - 1);
                    int    sender      = Int32.Parse(senderStr);    //the sender id
                    int    msgTS       = Int32.Parse(MsgStamp);
                    int    senderMsgNo = Int32.Parse(restOfString); //the no of msg from a particular sender

                    priority = Math.Max(priority + 1, msgTS);
                    TotalOrderMessage currentMsg = new TotalOrderMessage(data, sender, senderMsgNo, priority);
                    holdingQ.Add(currentMsg);
                    ReceivedBoxAppend(data);
                    //*** send proposed message
                    SendProposedMessage(sender, senderMsgNo, priority);
                    break;

                //msessage looks like: Proposed receiver sender msgno priority <EOM>
                case 'P':
                    string[] tokensP = data.Split('.');

                    if (Int32.Parse(tokensP[2]) == myID)
                    {
                        //ReceivedBoxAppend(data);
                        //int receiver = Int32.Parse(tokens[1]);
                        int thisMsgNo = Int32.Parse(tokensP[3]);
                        int thisPrio  = Int32.Parse(tokensP[4]);
                        proposedInfo[thisMsgNo].Add(thisPrio);
                        bool porposedFinished = false;
                        if (proposedInfo[thisMsgNo].Count == 5)
                        {
                            proposedInfo[thisMsgNo].Sort();
                            int maxPriority = proposedInfo[thisMsgNo].Last();
                            //send final
                            SendFinalMessage(thisMsgNo, maxPriority);
                            clock            = Math.Max(clock, maxPriority);
                            porposedFinished = true;
                        }
                        if (porposedFinished)
                        {
                            proposedInfo.Remove(thisMsgNo);
                        }
                    }
                    break;

                //msessage looks like: final sender msgno priority <EOM>
                case 'F':
                    //ReceivedBoxAppend(data);
                    string[] tokensF     = data.Split('.');
                    int      finalSender = Int32.Parse(tokensF[1]);
                    int      finalMsgNo  = Int32.Parse(tokensF[2]);
                    int      finalPrio   = Int32.Parse(tokensF[3]);

                    //TotalOrderMessage tom = holdingQ.Find(x => ());
                    bool succeed = SetMessagePriorityInQueue(finalSender, finalMsgNo, finalPrio);
                    if (!succeed)
                    {
                        Console.WriteLine("Error, cant find a final message in queue");
                        return;
                    }
                    holdingQ = sortHoldingQueue(holdingQ);
                    //if ((holdingQ.First().senderId != finalSender || holdingQ.First().senderMsgNo != finalMsgNo) && holdingQ.First().deliverable == true)
                    //    Console.WriteLine("assertion failed");

                    /*if (holdingQ.First().senderId == finalSender && holdingQ.First().senderMsgNo == finalMsgNo)
                     * {
                     *  TotalOrderMessage tommy = holdingQ.First();
                     *  ReadyBoxAppend(tommy);
                     *  deliveryQ.Add(tommy);
                     *  holdingQ.Remove(tommy);
                     *  clock = Math.Max(tommy.timeStamp, clock) + 1;
                     *  while (holdingQ.Count > 0 && holdingQ.First().deliverable == true)
                     *  {
                     *      TotalOrderMessage jerry = holdingQ.First();
                     *      ReadyBoxAppend(jerry);
                     *      deliveryQ.Add(jerry);
                     *      holdingQ.Remove(jerry);
                     *      clock = Math.Max(jerry.timeStamp, clock) + 1;
                     *  }
                     * }*/
                    while (holdingQ.Count > 0 && holdingQ.First().deliverable == true)
                    {
                        TotalOrderMessage jerry = holdingQ.First();
                        ReadyBoxAppend(jerry);
                        deliveryQ.Add(jerry);
                        holdingQ.Remove(jerry);
                        clock = Math.Max(jerry.timeStamp, clock) + 1;
                    }
                    break;
                }
                string display = "[";
                display      += clock;
                textBox1.Text = display + "]";
            }
        }
        catch (Exception ee)
        {
            Console.WriteLine(ee.ToString());
        }
    }
Ejemplo n.º 21
0
        public static void StartListening(string host, int port)
        {
            // Data buffer for incoming data.
            byte[] bytes = new Byte[1024];

            // Establish the local endpoint for the socket.
            // Dns.GetHostName returns the name of the
            // host running the application.
            IPHostEntry ipHostInfo = Dns.GetHostEntry(host);
            IPAddress   ipAddress  = ipHostInfo.AddressList[1];

            Console.WriteLine($"Server IP:{ipAddress}");

            IPEndPoint localEndPoint = new IPEndPoint(ipAddress, port);

            // Create a TCP/IP socket.
            Socket listener = new Socket(ipAddress.AddressFamily,
                                         SocketType.Stream, ProtocolType.Tcp);

            // Bind the socket to the local endpoint and
            // listen for incoming connections.
            try
            {
                listener.Bind(localEndPoint);
                listener.Listen(10);

                // Start listening for connections.
                while (true)
                {
                    Console.WriteLine("Waiting for a connection...");
                    // Program is suspended while waiting for an incoming connection.
                    Socket handler = listener.Accept();
                    data = null;

                    // An incoming connection needs to be processed.
                    while (true)
                    {
                        int bytesRec = handler.Receive(bytes);
                        data += Encoding.ASCII.GetString(bytes, 0, bytesRec);
                        // Show the data on the console.
                        Console.WriteLine("Text received : {0}", data);

                        // Echo the data back to the client.
                        byte[] replay = Encoding.ASCII.GetBytes(data);

                        handler.Send(replay);
                        if (data.IndexOf("<EOF>") > -1)
                        {
                            break;
                        }
                    }

                    // Show the data on the console.
                    Console.WriteLine("Text received : {0}", data);

                    // Echo the data back to the client.
                    byte[] msg = Encoding.ASCII.GetBytes(data);

                    handler.Send(msg);
                    handler.Shutdown(SocketShutdown.Both);
                    handler.Close();
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e.ToString());
            }

            Console.WriteLine("\nPress ENTER to continue...");
            Console.Read();
        }
Ejemplo n.º 22
0
    public void SendFinalMessage(int messageNo, int myPriority)
    {
        try
        {
            // Find the IP address of localhost
            IPHostEntry ipHostInfo = Dns.GetHostEntry(Dns.GetHostName());
            IPAddress   ipAddress  = null;
            foreach (IPAddress ip in ipHostInfo.AddressList)
            {
                if (ip.AddressFamily == AddressFamily.InterNetwork)
                {
                    ipAddress = ip;
                    break;
                }
            }
            IPEndPoint remoteEP = new IPEndPoint(ipAddress, 1081);
            Socket     sendSocket;
            try
            {
                // Create a TCP/IP  socket.
                sendSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

                // Connect to the Network
                sendSocket.Connect(remoteEP);

                // Generate and encode the multicast message into a byte array.

                // I removed the first space in this message
                //message looks like: Final.1.2.10.<EOM>
                string message = "Final." + myID + "." + messageNo + "." + myPriority + ".<EOM>\n";
                byte[] msg     = Encoding.ASCII.GetBytes(message);

                //SentBoxAppend(message);
                // Send the data to the network.
                int bytesSent = sendSocket.Send(msg);

                sendSocket.Shutdown(SocketShutdown.Both);
                sendSocket.Close();


                //Console.WriteLine("Press ENTER to terminate ...");
                //Console.ReadLine();
            }
            catch (ArgumentNullException ane)
            {
                Console.WriteLine("ArgumentNullException : {0}", ane.ToString());
            }
            catch (SocketException se)
            {
                Console.WriteLine("SocketException : {0}", se.ToString());
            }
            catch (Exception e)
            {
                Console.WriteLine("Unexpected exception : {0}", e.ToString());
            }
        }
        catch (Exception e)
        {
            Console.WriteLine(e.ToString());
        }
    }
Ejemplo n.º 23
0
        static void Main(string[] args)
        {
            String dc_address = "";

            if (args == null || args.Length <= 0)
            {
                Console.WriteLine("usage: SharpAdidnsdumpis.exe dc-address");
                return;
            }
            else
            {
                dc_address = args[0];
            }

            try
            {
                Console.WriteLine("Running enumeration against {0}", dc_address);

                String rootDn = "DC=DomainDnsZones";

                String domain_local = System.Net.NetworkInformation.IPGlobalProperties.GetIPGlobalProperties().DomainName;

                String domain_path = "";

                foreach (String domain_path_r in domain_local.Split('.'))
                {
                    domain_path += ",DC=" + domain_path_r;
                }

                rootDn += domain_path;

                Console.WriteLine("Running enumeration against {0}", "LDAP://" + dc_address + "/" + rootDn);

                DirectoryEntry rootEntry = new DirectoryEntry("LDAP://" + dc_address + "/" + rootDn);
                rootEntry.AuthenticationType = AuthenticationTypes.Delegation;
                DirectorySearcher searcher = new DirectorySearcher(rootEntry);

                //find domains
                var queryFormat = "(&(objectClass=DnsZone)(!(DC=*arpa))(!(DC=RootDNSServers)))";
                searcher.Filter      = queryFormat;
                searcher.SearchScope = SearchScope.Subtree;

                foreach (SearchResult result in searcher.FindAll())
                {
                    String domain = (result.Properties["DC"].Count > 0 ? result.Properties["DC"][0].ToString() : string.Empty);
                    Console.WriteLine();
                    Console.WriteLine();
                    Console.WriteLine("Domain: {0}", domain);
                    Console.WriteLine();

                    DirectoryEntry rootEntry_d = new DirectoryEntry("LDAP://" + dc_address + "/DC=" + result.Properties["DC"][0].ToString() + ",CN=microsoftdns," + rootDn);
                    rootEntry_d.AuthenticationType = AuthenticationTypes.Delegation;
                    DirectorySearcher searcher_h = new DirectorySearcher(rootEntry_d);

                    //find hosts
                    queryFormat            = "(&(!(objectClass=DnsZone))(!(DC=@))(!(DC=*arpa))(!(DC=*DNSZones)))";
                    searcher_h.Filter      = queryFormat;
                    searcher_h.SearchScope = SearchScope.Subtree;

                    foreach (SearchResult result_h in searcher_h.FindAll())
                    {
                        String target = "";

                        if (result_h.Properties["DC"].Count > 0)
                        {
                            target = result_h.Properties["DC"][0].ToString();
                        }
                        else
                        {
                            //Hidden entry
                            String path = result_h.Path;
                            target = (path.Substring(path.IndexOf("LDAP://" + dc_address + "/"), path.IndexOf(","))).Split('=')[1];
                        }

                        if (!target.EndsWith("."))
                        {
                            target += "." + domain;
                        }

                        Boolean tombstoned = result_h.Properties["dNSTombstoned"].Count > 0 ? (Boolean)result_h.Properties["dNSTombstoned"][0] : false;

                        try
                        {
                            IPHostEntry hostInfo = Dns.GetHostEntry(target);
                            foreach (IPAddress result_ip in hostInfo.AddressList)
                            {
                                Console.WriteLine("Host {0} {1}", target, result_ip);
                            }
                        }
                        catch (Exception e)
                        {
                            if (tombstoned)
                            {
                                Console.WriteLine("Host {0} Tombstoned", target);
                            }
                            else
                            {
                                Console.WriteLine("DNS Query with target : {0} failed", target);
                            }
                        }
                    }
                }

                Console.WriteLine();
                Console.WriteLine("SharpAdidnsdump end");
                Console.WriteLine();
                return;
            }
            catch (Exception e)
            {
                Console.WriteLine("Error retriving data : {0}", e.Message);
                return;
            }
        }
Ejemplo n.º 24
0
        public string lista(string operacion, String nombre, string apellido, int edad)
        {
            string cadena = operacion + nombre.ToString() + "," + apellido.ToString() + "," + edad.ToString();

            // Declara un bufer de  datos para recibir datos .
            byte[] bytes = new byte[1024];

            // Se conecta al dispositivo remoto .
            try
            {
                // Establece un punto remoto final para el socket.
                // Este ejemplo usa el puerto 11000 en la computadora local.
                IPHostEntry ipHostInfo = Dns.GetHostEntry(Dns.GetHostName());
                IPAddress   ipAddress  = ipHostInfo.AddressList[0];
                //               IPEndPopPnt remoteEP = new IPEndPoint(ipAddrPAdress.Paress, 11000);

                IPEndPoint remoteEP = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 11000);

                // Crear un socket TCP/IP  .
                Socket sender = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

                // Conetarse al punto final remoto  captura cualquier error .
                try
                {
                    sender.Connect(remoteEP);

                    sender.RemoteEndPoint.ToString();

                    // codifica datos en un string dentro de un arreglo de bits.

                    byte[] msg = Encoding.ASCII.GetBytes(cadena);

                    // Envia datos a traves del socket .
                    int bytesSent = sender.Send(msg);

                    // Recibe ladespuesta desde el dispositivo remoto .
                    int    bytesRec  = sender.Receive(bytes);
                    string respuesta = (Encoding.ASCII.GetString(bytes, 0, bytesRec));

                    // libera el socket.
                    sender.Shutdown(SocketShutdown.Both);
                    sender.Close();

                    return(respuesta);
                }
                catch (ArgumentNullException ane)
                {
                    Console.WriteLine("ArgumentNullException : {0}", ane.ToString());
                }
                catch (SocketException se)
                {
                    Console.WriteLine("SocketException : {0}", se.ToString());
                }
                catch (Exception e)
                {
                    Console.WriteLine("Error no manejado  : {0}", e.ToString());
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e.ToString());
            }
            return("no valido");
        }
Ejemplo n.º 25
0
        private static string GetServiceUrl(string url)
        {
            var serverAddress = Dns.GetHostEntry(Dns.GetHostName()).AddressList.FirstOrDefault(address => address.AddressFamily.Equals(AddressFamily.InterNetwork))?.ToString();

            return(url.Replace("*", serverAddress).Replace("*", serverAddress).Replace("localhost", serverAddress));
        }
Ejemplo n.º 26
0
        private static void ExecuteRequest(object arg)
        {
            try
            {
                using (Socket myClient = (Socket)arg)
                {
                    if (myClient.Connected)
                    {
                        byte[] httpRequest = ReadToEnd(myClient);


                        Parser http = new Parser(httpRequest);

                        if (http.Items == null || http.Items.Count <= 0 || !http.Items.ContainsKey("Host"))
                        {
                            WriteLog("REQUEST {0} bytes, headers not found.", httpRequest.Length);
                        }
                        else
                        {
                            WriteLog("REQUEST {0} bytes, method{1}, host {2}:{3}", httpRequest.Length, http.Method, http.Host, http.Port);
                            // WriteLog(http.GetHeadersAsString());


                            byte[] response = null;


                            if (_NeedAuth)
                            {
                                if (!http.Items.ContainsKey("Authorization"))
                                {
                                    response = GetHTTPError(401, "Unauthorized");
                                    myClient.Send(response, response.Length, SocketFlags.None);
                                    return;
                                }
                                else
                                {
                                    string auth  = Encoding.UTF8.GetString(Convert.FromBase64String(http.Items["Authorization"].Source.Replace("Basic ", "")));
                                    string login = auth.Split(":".ToCharArray())[0];
                                    string pwd   = auth.Split(":".ToCharArray())[1];
                                    if (_Login != login || _Password != pwd)
                                    {
                                        // wrong login or password
                                        response = GetHTTPError(401, "Unauthorized");
                                        myClient.Send(response, response.Length, SocketFlags.None);
                                        return;
                                    }
                                }
                            }

                            //check blacklist
                            if (_AllowBlackList && _BlackList != null && Array.IndexOf(_BlackList, http.Host.ToLower()) != -1)
                            {
                                response = GetHTTPError(403, "Forbidden");
                                myClient.Send(response, response.Length, SocketFlags.None);
                                return;
                            }


                            bool ready = false;
                            if (UseCache)
                            {
                                if (Cache.HasResource(http.Path))
                                {
                                    ready    = true;
                                    response = Cache.GetData(http.Path);
                                    if (response != null)
                                    {
                                        myClient.Send(response, response.Length, SocketFlags.None);
                                    }
                                }
                            }
                            if (!ready)
                            {
                                IPHostEntry myIPHostEntry = Dns.GetHostEntry(http.Host);

                                if (myIPHostEntry == null || myIPHostEntry.AddressList == null || myIPHostEntry.AddressList.Length <= 0)
                                {
                                    WriteLog("Can't determine IP-adress by host {0}.", http.Host);
                                }
                                else
                                {
                                    IPEndPoint myIPEndPoint = new IPEndPoint(myIPHostEntry.AddressList[0], http.Port);


                                    if (http.Method == Parser.MethodsList.CONNECT)
                                    {
                                        WriteLog("Protocol HTTPS not impemented.");
                                        response = GetHTTPError(501, "Not Implemented");
                                    } // HTTP.Parser.MethodsList.CONNECT
                                    else
                                    {
                                        //if (!ready)
                                        {
                                            //redirect
                                            using (Socket myRerouting = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
                                            {
                                                myRerouting.Connect(myIPEndPoint);
                                                if (myRerouting.Send(httpRequest, httpRequest.Length, SocketFlags.None) != httpRequest.Length)
                                                {
                                                    WriteLog("Data to host {0} was not sended...", http.Host);
                                                }
                                                else
                                                {
                                                    //getting answer
                                                    Parser httpResponse = new Parser(ReadToEnd(myRerouting));
                                                    if (httpResponse.Source != null && httpResponse.Source.Length > 0)
                                                    {
                                                        WriteLog("Request recieved {0} bytes, status code {1}", httpResponse.Source.Length, httpResponse.StatusCode);
                                                        // WriteLog(httpResponse.GetHeadersAsString());


                                                        response = httpResponse.Source;


                                                        switch (httpResponse.StatusCode)
                                                        {
                                                        case 400:
                                                        case 403:
                                                        case 404:
                                                        case 407:
                                                        case 500:
                                                        case 501:
                                                        case 502:
                                                        case 503:
                                                            response = GetHTTPError(httpResponse.StatusCode, httpResponse.StatusMessage);
                                                            break;

                                                        default:

                                                            if (_AppendHtml)
                                                            {
                                                                //check if html
                                                                if (httpResponse.Items.ContainsKey("Content-Type") && ((ItemContentType)httpResponse.Items["Content-Type"]).Value == "text/html")
                                                                {
                                                                    //get body
                                                                    string body = httpResponse.GetBodyAsString();


                                                                    body = Regex.Replace(body, "<title>(?<title>.*?)</title>", "<title>ProxyServer - $1</title>");


                                                                    body = Regex.Replace(body, "(<body.*?>)", "$1<div style='height:20px;width:100%;background-color:black;color:white;font-weight:bold;text-align:center;'>Example of Proxy Server</div>");


                                                                    httpResponse.SetStringBody(body);


                                                                    response = httpResponse.Source;
                                                                }
                                                            }
                                                            //you can change image data too
                                                            break;
                                                        }
                                                    }
                                                    else
                                                    {
                                                        WriteLog("Recieved answer 0 byte");
                                                    }
                                                }
                                                myRerouting.Close();
                                            }
                                        } // HTTP.Parser.MethodsList.CONNECT
                                        if (AllowStoreInCache)
                                        {
                                            Cache.SetData(http.Path, response);
                                        }
                                    }

                                    if (response != null)
                                    {
                                        myClient.Send(response, response.Length, SocketFlags.None);
                                    }
                                }
                            }
                        }


                        myClient.Close();
                    }
                }
            }
            catch (Exception ex)
            {
                WriteLog("Error: ", ex.Message);
            }
        }
Ejemplo n.º 27
0
        /// <summary>
        /// Creates an <see cref="IPEndPoint"/> for the specified host name and port number.
        /// </summary>
        /// <param name="hostNameOrAddress">The host name or IP address to resolve.</param>
        /// <param name="port">The port number to be associated with the address.</param>
        /// <param name="stack">Desired IP stack to use.</param>
        /// <returns>An <see cref="IPEndPoint"/> object.</returns>
        public static IPEndPoint CreateEndPoint(string hostNameOrAddress, int port, IPStack stack)
        {
            // Determine system's default IP stack if the default stack was requested
            if (stack == IPStack.Default)
            {
                stack = GetDefaultIPStack();
            }

            // Make sure system can support specified stack
            if (stack == IPStack.IPv6 && !Socket.OSSupportsIPv6)
            {
                throw new NotSupportedException($"IPv6 stack is not available for socket creation on {hostNameOrAddress.ToNonNullNorWhiteSpace("localhost")}:{port}");
            }
#if !MONO
            if (stack == IPStack.IPv4 && !Socket.OSSupportsIPv4)
            {
                throw new NotSupportedException($"IPv4 stack is not available for socket creation on {hostNameOrAddress.ToNonNullNorWhiteSpace("localhost")}:{port}");
            }
#endif

            if (string.IsNullOrWhiteSpace(hostNameOrAddress))
            {
                // No host name or IP address was specified, use local IPs
                if (stack == IPStack.IPv6)
                {
                    return(new IPEndPoint(IPAddress.IPv6Any, port));
                }

                return(new IPEndPoint(IPAddress.Any, port));
            }

            IPAddress address;
            bool      ipStackMismatch = false;

            // Attempt to parse provided address name as a literal IP address
            if (IPAddress.TryParse(hostNameOrAddress, out address))
            {
                // As long as desired IP stack matches format of specified IP address, return end point for address
                if ((stack == IPStack.IPv6 && address.AddressFamily == AddressFamily.InterNetworkV6) ||
                    (stack == IPStack.IPv4 && address.AddressFamily == AddressFamily.InterNetwork))
                {
                    return(new IPEndPoint(address, port));
                }

                // User specified an IP address that is mismatch with the desired IP stack. If the DNS server
                // responds to this IP, we can attempt to see if an IP is defined for the desired IP stack,
                // otherwise this is an exception
                ipStackMismatch = true;
            }

            try
            {
                // Handle "localhost" as a special case, returning proper loopback address for the desired IP stack
                if (string.Compare(hostNameOrAddress, "localhost", true) == 0)
                {
                    return(new IPEndPoint(stack == IPStack.IPv6 ? IPAddress.IPv6Loopback : IPAddress.Loopback, port));
                }

                // Failed to parse an IP address for the desired stack - this may simply be that a host name was provided
                // so we attempt a DNS lookup. Note that exceptions will occur if DNS lookup fails.
                IPAddress[] dnsAddressList = Dns.GetHostEntry(hostNameOrAddress).AddressList;

                if (dnsAddressList.Length > 0)
                {
                    // Traverse address list looking for first match on desired IP stack
                    foreach (IPAddress dnsAddress in dnsAddressList)
                    {
                        if ((stack == IPStack.IPv6 && dnsAddress.AddressFamily == AddressFamily.InterNetworkV6) ||
                            (stack == IPStack.IPv4 && dnsAddress.AddressFamily == AddressFamily.InterNetwork))
                        {
                            return(new IPEndPoint(dnsAddress, port));
                        }
                    }

                    // If no available matching address was found for desired IP stack, this is an IP stack mismatch
                    ipStackMismatch = true;
                }

                throw new InvalidOperationException($"No valid {stack} addresses could be found for \"{hostNameOrAddress}\"");
            }
            catch
            {
                // Spell out a specific error message for IP stack mismatches
                if (ipStackMismatch)
                {
                    throw new InvalidOperationException($"IP address mismatch: unable to find an {stack} address for \"{hostNameOrAddress}\"");
                }

                // Otherwise report original exception
                throw;
            }
        }
Ejemplo n.º 28
0
        private async Task DataUpdateStepAsync(WaterfallStepContext stepContext, CancellationToken cancellationToken)
        {
            var orderData = await _orderDataAccessor.GetAsync(stepContext.Context, () => new OrderData(), cancellationToken);

            CosmosClient client = new CosmosClient(Startup.CosmosDbEndpoint, Startup.AuthKey);

            database = await client.CreateDatabaseIfNotExistsAsync(databaseId);

            ContainerProperties containerProperties = new ContainerProperties(containerId, partitionKeyPath: Startup.PartitionKey);

            // Create with a throughput of 1000 RU/s
            container = await database.CreateContainerIfNotExistsAsync(
                containerProperties,
                throughput : 1000);

            //orderNum 가져오기
            try
            {
                FeedIterator <DBdata> feedIterator = container.GetItemQueryIterator <DBdata>("SELECT top 1 * FROM c order by c._ts desc");
                {
                    while (feedIterator.HasMoreResults)
                    {
                        FeedResponse <DBdata> result = await feedIterator.ReadNextAsync();

                        foreach (var item in result)
                        {
                            orderData.OrderNum = Int32.Parse(item.id);
                        }
                    }
                }
            }
            catch (System.Exception e)
            {
                orderData.OrderNum = 0;
            }

            //ip
            IPHostEntry host   = Dns.GetHostEntry(Dns.GetHostName());
            string      ipAddr = string.Empty;

            for (int i = 0; i < host.AddressList.Length; i++)
            {
                if (host.AddressList[i].AddressFamily == AddressFamily.InterNetwork)
                {
                    ipAddr = host.AddressList[i].ToString();
                }
            }

            //Order 데이터 삽입
            foreach (Sandwich tempSand in orderData.Sandwiches)
            {
                string sJson = JsonConvert.SerializeObject(tempSand);

                var dbData = new DBdata {
                    id = $"{++orderData.OrderNum}", Contents = tempSand, ETag = "x", AccountNumber = ipAddr
                };

                await container.CreateItemAsync <DBdata>(dbData, new PartitionKey(dbData.AccountNumber));
            }

            //container 변경
            containerProperties = new ContainerProperties(countContainerId, partitionKeyPath: "/AccountNumber");
            // Create with a throughput of 1000 RU/s
            container = await database.CreateContainerIfNotExistsAsync(
                containerProperties,
                throughput : 1000);

            //Count 데이터 삽입
            foreach (Sandwich tempSand in orderData.Sandwiches)
            {
                var    CountId = 0;
                string sauce   = "";
                tempSand.Sauce.Sort();
                foreach (string temp in tempSand.Sauce)
                {
                    sauce += temp + " ";
                }

                //CountId 찾기
                try
                {
                    FeedIterator <DBcount> feedIterator = container.GetItemQueryIterator <DBcount>("SELECT top 1 * FROM c order by c._ts desc");
                    {
                        while (feedIterator.HasMoreResults)
                        {
                            FeedResponse <DBcount> result = await feedIterator.ReadNextAsync();

                            foreach (var item in result)
                            {
                                CountId = Int32.Parse(item.id) + 1;
                            }
                        }
                    }
                }
                catch (System.Exception e)
                {
                    CountId = 0;
                }

                try {
                    FeedIterator <DBcount> feedIterator = container.GetItemQueryIterator <DBcount>("SELECT * FROM c WHERE c.Sauce='" + sauce + "' and c.Bread ='" + tempSand.Bread + "' and c.Menu ='" + tempSand.Menu + "'");
                    {
                        if (feedIterator.HasMoreResults)
                        {
                            FeedResponse <DBcount> result = await feedIterator.ReadNextAsync();

                            DBcount res                 = result.First();
                            var     count               = res.Count + 1;
                            DBcount countData           = new DBcount(); countData.id = res.id; countData.Count = count; countData.Sauce = sauce; countData.Menu = tempSand.Menu; countData.ETag = "x"; countData.AccountNumber = "0"; countData.Bread = tempSand.Bread;
                            ItemResponse <DBcount> item = await container.DeleteItemAsync <DBcount>(partitionKey : new PartitionKey("0"), id : res.id);

                            await container.CreateItemAsync(countData, new PartitionKey("0"));
                        }
                    }
                }
                catch (System.Exception e)
                {
                    var countData = new DBcount {
                        id = $"{CountId}", Count = 1, Bread = $"{tempSand.Bread}", Sauce = sauce, Menu = $"{tempSand.Menu}", ETag = "x", AccountNumber = "0"
                    };
                    await container.CreateItemAsync <DBcount>(countData, new PartitionKey("0"));
                }
            }
        }
Ejemplo n.º 29
0
        //var ip = HttpContext.Request.Host;
        // var remoteIpAddress = Request.Host.Host;
        public static string GetIPClient()
        {
            IPHostEntry heserver = Dns.GetHostEntry(Dns.GetHostName());

            return(heserver.AddressList.ToList().Where(p => p.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork).FirstOrDefault().ToString());
        }
Ejemplo n.º 30
0
        /// <summary>
        /// initialize pomelo client
        /// </summary>
        /// <param name="host">server name or server ip (www.xxx.com/127.0.0.1/::1/localhost etc.)</param>
        /// <param name="port">server port</param>
        /// <param name="callback">socket successfully connected callback(in network thread)</param>
        public void initClient(string host, int port, Action callback = null)
        {
            timeoutEvent.Reset();
            eventManager = new EventManager();
            NetWorkChanged(NetWorkState.CONNECTING);

            IPAddress ipAddress   = null;
            IPAddress ipAddressV6 = null;

            try
            {
                IPAddress[] addresses = Dns.GetHostEntry(host).AddressList;
                foreach (var item in addresses)
                {
                    if (item.AddressFamily == AddressFamily.InterNetworkV6)
                    {
                        ipAddressV6 = item;
                        break;
                    }
                }
                if (ipAddressV6 == null)
                {
                    foreach (var item in addresses)
                    {
                        if (item.AddressFamily == AddressFamily.InterNetwork)
                        {
                            ipAddress = item;
                            break;
                        }
                    }
                }
            }
            catch (Exception e)
            {
                NetWorkChanged(NetWorkState.ERROR);
                return;
            }

            if (ipAddressV6 == null && ipAddress == null)
            {
                throw new Exception("can not parse host : " + host);
            }

            IPEndPoint ie = null;

            if (ipAddressV6 != null)
            {
                this.socket = new Socket(AddressFamily.InterNetworkV6, SocketType.Stream, ProtocolType.Tcp);
                ie          = new IPEndPoint(ipAddressV6, port);
            }
            else
            {
                this.socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                ie          = new IPEndPoint(ipAddress, port);
            }

            socket.BeginConnect(ie, new AsyncCallback((result) =>
            {
                try
                {
                    this.socket.EndConnect(result);
                    this.protocol = new Protocol(this, this.socket);
                    NetWorkChanged(NetWorkState.CONNECTED);

                    if (callback != null)
                    {
                        callback();
                    }
                }
                catch (SocketException e)
                {
                    if (netWorkState != NetWorkState.TIMEOUT)
                    {
                        NetWorkChanged(NetWorkState.ERROR);
                    }
                    Dispose();
                }
                finally
                {
                    timeoutEvent.Set();
                }
            }), this.socket);

            if (timeoutEvent.WaitOne(timeoutMSec, false))
            {
                if (netWorkState != NetWorkState.CONNECTED && netWorkState != NetWorkState.ERROR)
                {
                    NetWorkChanged(NetWorkState.TIMEOUT);
                    Dispose();
                }
            }
        }