Example #1
0
        private void ConfigureNetworkAddressChangedHandler()
        {
            NetworkChange.NetworkAddressChanged += new NetworkAddressChangedEventHandler((sender, e) =>
            {
                // Enumerate the connected network interfaces
                var networks             = NetworkListManager.GetNetworks(NetworkConnectivityLevels.Connected).GetEnumerator();
                var newConnectedNetworks = new List <Microsoft.WindowsAPICodePack.Net.Network>();
                while (networks.MoveNext())
                {
                    // Ignore the tunnel network interface and include everything else
                    if (networks.Current.Name != ProductConstants.InternalAppName)
                    {
                        newConnectedNetworks.Add(networks.Current);
                    }
                }

                if (newConnectedNetworks.Count > 0)
                {
                    // Compare the network ids to confirm if a network change occured
                    var connectedNetworkIds    = new HashSet <Guid>(connectedNetworks.Select(n => n.NetworkId).ToList());
                    var newConnectedNetworkIds = new HashSet <Guid>(newConnectedNetworks.Select(n => n.NetworkId).ToList());

                    if (!connectedNetworkIds.SetEquals(newConnectedNetworkIds))
                    {
                        connectedNetworks = newConnectedNetworks;

                        // Validate the set of network ids, filtering out the networks that are obsolete
                        if (ValidateNetworkIds(connectedNetworkIds) && ValidateNetworkIds(newConnectedNetworkIds))
                        {
                            CaptivePortalDetected = false;
                        }
                    }
                }
            });
        }
Example #2
0
        /// <summary>
        /// Get the Adapter ID from the supplied network ID
        /// </summary>
        /// <param name="vNetworkID"></param>
        /// <param name="vConnectivityLevels"></param>
        /// <returns></returns>
        public static Guid getAdapterID(string vNetworkID, NetworkConnectivityLevels vConnectivityLevels)
        {
            Guid output = new Guid();

            NetworkCollection netCollection = NetworkListManager.GetNetworks(vConnectivityLevels);

            foreach (Network n in netCollection)
            {
                string nID = n.NetworkId.ToString();
                //if (nID.Equals(vNetworkID.ToString().ToUpper()))
                if (nID == vNetworkID.ToString())
                {
                    foreach (NetworkConnection c in n.Connections)
                    {
                        if (c.Network.NetworkId == n.NetworkId)
                        {
                            output = c.AdapterId;
                            break;
                        }
                    }
                }
            }

            return(output);
        }
Example #3
0
        static void Main(string[] args)
        {
            // check the internet connection state
            bool isInternetConnected =
                NetworkListManager.IsConnectedToInternet;

            Console.WriteLine("Machine connected to Internet: {0}",
                              isInternetConnected);

            if (isInternetConnected)
            {
                // get the list of all network connections
                NetworkCollection netCollection =
                    NetworkListManager.GetNetworks(NetworkConnectivityLevels.Connected);

                // work through the set of connections and write out the
                // name of those which are connected to the internet
                foreach (Network network in netCollection)
                {
                    if (network.IsConnectedToInternet)
                    {
                        Console.WriteLine("Connection {0} is connected to the internet",
                                          network.Name);
                    }
                }
            }

            Console.WriteLine("\nMain method complete. Press Enter.");
            Console.ReadLine();
        }
Example #4
0
        /* Lists connected networks by profile */
        public List <string> NetworksByProfileList(NET_FW_PROFILE_TYPE2_ profile, NetworkConnectivityLevels level = NetworkConnectivityLevels.All)
        {
            List <string>   networks    = new List <string>();
            NetworkCategory profileName = NetworkCategory.Public;

            switch (profile)
            {
            case NET_FW_PROFILE_TYPE2_.NET_FW_PROFILE2_DOMAIN:
                profileName = NetworkCategory.Authenticated;
                break;

            case NET_FW_PROFILE_TYPE2_.NET_FW_PROFILE2_PRIVATE:
                profileName = NetworkCategory.Private;
                break;

            case NET_FW_PROFILE_TYPE2_.NET_FW_PROFILE2_PUBLIC:
                profileName = NetworkCategory.Public;
                break;
            }

            //Install-Package WindowsAPICodePack-Core
            NetworkCollection nCollection = NetworkListManager.GetNetworks(level);

            foreach (Network net in nCollection)
            {
                if (net.Category == profileName)
                {
                    networks.Add(net.Name);
                }
            }
            return(networks);
        }
Example #5
0
        private void GetWindowsNetworkConnection()
        {
            var dnsSrv = new DNSService();

            byte priority          = 1;
            var  networkCollection = NetworkListManager.GetNetworks(NetworkConnectivityLevels.All);

            foreach (var network in networkCollection)
            {
                var netAdapter = new NetworkAdapter {
                    Name = network.Name, AdapterId = network.NetworkId, IsConnected = network.IsConnectedToInternet
                };
                cmbNetworkConnection.Items.Add(network.Name);
                if (network.IsConnected && network.IsConnectedToInternet)
                {
                    netAdapter.ConnectionCollection = network.Connections;
                    netAdapter.Description          = dnsSrv.Current(network.Connections).Description;
                    netAdapter.DnsAddress           = dnsSrv.Get(network.Connections);
                    netAdapter.Priority             = priority;
                    priority++;
                }
                _networkAdapters.Add(netAdapter);
            }

            _connectedNetwork = _networkAdapters.SingleOrDefault(s => s.Priority == 1);
            SetCurrentDNSIPs(_connectedNetwork.DnsAddress);
            SetConnectionImage();
        }
        /// <summary>
        /// fill the network combo box list with a custom combo box item
        /// </summary>
        /// <param name="vSelectedNetworkName"></param>
        /// <param name="vConnectivity"></param>
        private void FillNetworkList(string vSelectedNetworkName, NetworkConnectivityLevels vConnectivity)
        {
            cbNetwork.Items.Clear();

            NetworkCollection  netCollection = NetworkListManager.GetNetworks(vConnectivity); // NetworkConnectivityLevels.Connected);
            ComboboxItemCustom comboItem;

            var orderedList =
                netCollection.OrderBy(x => x.Name);

            //.ThenByDescending(x => x.Name);

            foreach (Network n in orderedList)
            {
                {
                    comboItem = new ComboboxItemCustom(n.Name, n.NetworkId.ToString(), n.IsConnectedToInternet);
                    cbNetwork.Items.Add(comboItem);

                    if (vSelectedNetworkName == n.Name)
                    {
                        cbNetwork.SelectedItem = comboItem;
                    }
                }
            }

            if (String.IsNullOrEmpty(vSelectedNetworkName))
            {
                cbNetwork.Text = "(Select One)";
            }
        }
Example #7
0
        public static Network GetNetwork(TimeSpan?timeout = null)
        {
            Network result = default;

            Stopwatch stopwatch = Stopwatch.StartNew();

            do
            {
                // Windows API code pack can show stale adapters, and incorrect names.
                // First, get the real interface here.
                if (NetworkInterface.GetAllNetworkInterfaces().FirstOrDefault(i => i.Name == WireGuardServerInterfaceName) is { } networkInterface)
                {
                    // Now use the ID to get the network from API code pack
                    if (NetworkListManager.GetNetworks(NetworkConnectivityLevels.All).FirstOrDefault(n => n.Connections.Any(c => c.AdapterId == new Guid(networkInterface.Id))) is { } network)
                    {
                        result = network;
                        break;
                    }
                }
            } while (stopwatch.ElapsedMilliseconds < (timeout?.TotalMilliseconds ?? 0));

            stopwatch.Stop();

            return(result);
        }
        public string GetNetworkNameConnectedToInternet()
        {
            if (!_netManager.IsConnectedToInternet)
            {
                return(null);
            }
            var connected = _netManager.GetNetworks(NLM_ENUM_NETWORK.NLM_ENUM_NETWORK_CONNECTED);

            foreach (INetwork network in connected)
            {
                if (network.IsConnectedToInternet)
                {
                    return(network.GetName());
                }
            }
            return(null);
        }
Example #9
0
        private static NetworkCollection GetNetworks()
        {
            // var nlm = new NetworkListManager();
            var networks = NetworkListManager.GetNetworks(NetworkConnectivityLevels.Connected);

            // IEnumNetworks networks = nlm.GetNetworks(NLM_ENUM_NETWORK.NLM_ENUM_NETWORK_ALL);
            foreach (var network in networks)
            {
                string sConnected = ((network.IsConnected == true) ? " (connected)" : " (disconnected)");
                Console.WriteLine("Network : " + network.Name + " - Category : " + network.Category.ToString() + sConnected);
            }

            return(networks);
        }
Example #10
0
        // 检查网络是否连接
        private bool IsNetworkConnected()
        {
            bool isConn = false;
            NetworkCollection networks = NetworkListManager.GetNetworks(NetworkConnectivityLevels.All);

            foreach (Network n in networks)
            {
                if (n.IsConnected)//&& n.IsConnectedToInternet)
                {
                    isConn = true;
                    break;
                }
            }
            return(isConn);
        }
Example #11
0
        /// <summary>
        /// Returns the name of the connected network.
        /// </summary>
        /// <param name="neti"></param>
        /// <returns></returns>
        public static string GetConnectedNetworks(NetworkInterface neti)
        {
            var connectedNet = NetworkListManager.GetNetworks(NetworkConnectivityLevels.Connected);

            foreach (var net in connectedNet)
            {
                foreach (var conn in net.Connections)
                {
                    if (conn.AdapterId == Guid.Parse(neti.Id))
                    {
                        return(net.Name);
                    }
                }
            }
            return("");
        }
Example #12
0
        internal void CheckNetwork()
        {
            if (wakeNetworks != null)
            {
                bool connected = false;
                foreach (Network network in NetworkListManager.GetNetworks(NetworkConnectivityLevels.Connected))
                {
                    if (wakeNetworks.Contains(network.Name.ToLower()) || wakeNetworks.Contains(network.NetworkId.ToString().ToLower()))
                    {
                        connected = true;
                    }
                }

                IsNetworkConnected = connected;
            }
        }
    static void Main(string[] args)
    {
        var mgr = new NetworkListManager();

        foreach (INetwork network in mgr.GetNetworks(NLM_ENUM_NETWORK.NLM_ENUM_NETWORK_ALL))
        {
            Console.WriteLine("Network: " + network.GetName());
            foreach (INetworkConnection conn in network.GetNetworkConnections())
            {
                Console.WriteLine(" Adapter Id:  " + conn.GetAdapterId());
                var ni = NetworkInterface.GetAllNetworkInterfaces().FirstOrDefault(i => new Guid(i.Id) == conn.GetAdapterId());
                Console.WriteLine(" Interface: " + ni.Name);
                Console.WriteLine(" Type: " + ni.NetworkInterfaceType);
            }
        }
    }
Example #14
0
        private void LoadNetworkConnections()
        {
            NetworkCollection networks = NetworkListManager.GetNetworks(NetworkConnectivityLevels.All);

            foreach (Network n in networks)
            {
                // Create a tab
                TabItem tabItem = new TabItem();
                tabItem.Header = string.Format("Network {0} ({1})", tabControl1.Items.Count, n.Name);
                tabControl1.Items.Add(tabItem);

                //
                StackPanel stackPanel2 = new StackPanel();
                stackPanel2.Orientation = Orientation.Vertical;

                // List all the properties
                AddProperty("Name: ", n.Name, stackPanel2);
                AddProperty("Description: ", n.Description, stackPanel2);
                AddProperty("Domain type: ", n.DomainType.ToString(), stackPanel2);
                AddProperty("Is connected: ", n.IsConnected.ToString(), stackPanel2);
                AddProperty("Is connected to the internet: ", n.IsConnectedToInternet.ToString(), stackPanel2);
                AddProperty("Network ID: ", n.NetworkId.ToString(), stackPanel2);
                AddProperty("Category: ", n.Category.ToString(), stackPanel2);
                AddProperty("Created time: ", n.CreatedTime.ToString(), stackPanel2);
                AddProperty("Connected time: ", n.ConnectedTime.ToString(), stackPanel2);
                AddProperty("Connectivity: ", n.Connectivity.ToString(), stackPanel2);

                //
                StringBuilder s = new StringBuilder();
                s.AppendLine("Network Connections:");
                NetworkConnectionCollection connections = n.Connections;
                foreach (NetworkConnection nc in connections)
                {
                    s.AppendFormat("\n\tConnection ID: {0}\n\tDomain: {1}\n\tIs connected: {2}\n\tIs connected to internet: {3}\n",
                                   nc.ConnectionId, nc.DomainType, nc.IsConnected, nc.IsConnectedToInternet);
                    s.AppendFormat("\tAdapter ID: {0}\n\tConnectivity: {1}\n",
                                   nc.AdapterId, nc.Connectivity);
                }
                s.AppendLine();

                Label label = new Label();
                label.Content = s.ToString();

                stackPanel2.Children.Add(label);
                tabItem.Content = stackPanel2;
            }
        }
Example #15
0
        /// <summary>
        /// Get the information on if the network is connected, and connected to the internet
        /// </summary>
        /// <param name="vNetworkName"></param>
        /// <param name="vConnectivityLevels"></param>
        /// <param name="vIsConnected"></param>
        /// <param name="vIsConnectedToInternet"></param>
        public static void getNetworkConnectionInfo(String vNetworkName, NetworkConnectivityLevels vConnectivityLevels, out bool vIsConnected, out bool vIsConnectedToInternet)
        {
            vIsConnected           = false;
            vIsConnectedToInternet = false;

            NetworkCollection netCollection = NetworkListManager.GetNetworks(vConnectivityLevels);

            foreach (Network n in netCollection)
            {
                if (n.Name == vNetworkName)
                {
                    vIsConnected           = n.IsConnected;
                    vIsConnectedToInternet = n.IsConnectedToInternet;
                    break;
                }
            }
        }
        private void LoadNetworkConnections()
        {
            var networks = NetworkListManager.GetNetworks(NetworkConnectivityLevels.All);

            foreach (var n in networks)
            {
                var tabItem = new TabItem {
                    Header = string.Format("Network {0} ({1})", TabControl1.Items.Count, n.Name)
                };
                TabControl1.Items.Add(tabItem);
                var stackPanel2 = new StackPanel {
                    Orientation = Orientation.Vertical
                };

                AddProperty("Name: ", n.Name, stackPanel2);
                AddProperty("Description: ", n.Description, stackPanel2);
                AddProperty("Domain type: ", n.DomainType.ToString(), stackPanel2);
                AddProperty("Is connected: ", n.IsConnected.ToString(), stackPanel2);
                AddProperty("Is connected to the internet: ", n.IsConnectedToInternet.ToString(), stackPanel2);
                AddProperty("Network ID: ", n.NetworkId.ToString(), stackPanel2);
                AddProperty("Category: ", n.Category.ToString(), stackPanel2);
                AddProperty("Created time: ", n.CreatedTime.ToString(CultureInfo.InvariantCulture), stackPanel2);
                AddProperty("Connected time: ", n.ConnectedTime.ToString(CultureInfo.InvariantCulture), stackPanel2);
                AddProperty("Connectivity: ", n.Connectivity.ToString(), stackPanel2);

                var s = new StringBuilder();
                s.AppendLine("Network Connections:");
                var connections = n.Connections;
                foreach (var nc in connections)
                {
                    s.AppendFormat(
                        "\n\tConnection ID: {0}\n\tDomain: {1}\n\tIs connected: {2}\n\tIs connected to internet: {3}\n",
                        nc.ConnectionId, nc.DomainType, nc.IsConnected, nc.IsConnectedToInternet);
                    s.AppendFormat("\tAdapter ID: {0}\n\tConnectivity: {1}\n",
                                   nc.AdapterId, nc.Connectivity);
                }
                s.AppendLine();

                var label = new Label {
                    Content = s.ToString()
                };

                stackPanel2.Children.Add(label);
                tabItem.Content = stackPanel2;
            }
        }
Example #17
0
        public void NetworkCollectionContainsAllNetworkConnections()
        {
            bool isConnected = NetworkListManager.IsConnected;
            ConnectivityStates connectivity = NetworkListManager.Connectivity;
            bool isConnectedToInternet      = NetworkListManager.IsConnectedToInternet;

            NetworkCollection           networks    = NetworkListManager.GetNetworks(NetworkConnectivityLevels.All);
            NetworkConnectionCollection connections = NetworkListManager.GetNetworkConnections();

            // BUG: Both GetNetworks and GetNetworkConnections create new network objects, so
            // you can't do a reference comparison.
            // By inspection, the connections are contained in the NetworkCollection, just a different instance.
            foreach (NetworkConnection c in connections)
            {
                Assert.Contains(c.Network, networks);
            }
        }
Example #18
0
        /// <summary>
        /// Get the ID for the network from the name/ssid
        /// </summary>
        /// <param name="vNetworkName"></param>
        /// <param name="vConnectivityLevels"></param>
        /// <returns></returns>
        public static Guid getNetworkID(String vNetworkName, NetworkConnectivityLevels vConnectivityLevels)
        {
            Guid output = new Guid();

            NetworkCollection netCollection = NetworkListManager.GetNetworks(vConnectivityLevels);

            foreach (Network n in netCollection)
            {
                if (n.Name == vNetworkName)
                {
                    output = n.NetworkId;
                    break;
                }
            }

            return(output);
        }
Example #19
0
        /// <summary>
        /// Get the network name from the ID
        /// </summary>
        /// <param name="vNetworkId"></param>
        /// <param name="vConnectivityLevels"></param>
        /// <returns></returns>
        public static string getNetworkName(Guid vNetworkId, NetworkConnectivityLevels vConnectivityLevels)
        {
            string output = string.Empty;

            NetworkCollection netCollection = NetworkListManager.GetNetworks(vConnectivityLevels);

            foreach (Network n in netCollection)
            {
                if (n.NetworkId == vNetworkId)
                {
                    output = n.Name;
                    break;
                }
            }

            return(output);
        }
        public static void TestNetwork()
        {
            NetworkCollection networks = NetworkListManager.GetNetworks(NetworkConnectivityLevels.Connected);

            Console.WriteLine("\t[NetworkConnections]");

            foreach (Network n in networks)
            {
                if (n.Description.StartsWith("Aspit"))
                {
                    SQLDB.SetConString("DBConInternal");
                }
                else
                {
                    SQLDB.SetConString("DBCon");
                }
            }
        }
Example #21
0
        private void btnAgBaglantisi_Click(object sender, EventArgs e)
        {
            NetworkCollection networks = NetworkListManager.
                                         GetNetworks(NetworkConnectivityLevels.All);

            foreach (Network n in networks)
            {
                TreeNode ana_dugum = new TreeNode();
                ana_dugum.Text = string.Format("Network {0} ({1})",
                                               treeView1.Nodes.Count, "Bağlantı İsmi= " + n.Name);
                treeView1.Nodes.Add(ana_dugum);

                ana_dugum.Nodes.Add("Tanımlama= " + n.Description);
                ana_dugum.Nodes.Add("Domain türü=" + n.DomainType);
                if (n.IsConnected == true)
                {
                    ana_dugum.Nodes.Add("Ağ Bağlantısı Açık");
                }
                else
                {
                    ana_dugum.Nodes.Add("Ağ Bağlantısı Kapalı");
                }
                if (n.IsConnectedToInternet == true)
                {
                    ana_dugum.Nodes.Add("İnternet Bağlantısı Var");
                }
                else
                {
                    ana_dugum.Nodes.Add("İnternet Bağlantısı Yok");
                }
                ana_dugum.Nodes.Add("Network Id=" +
                                    n.NetworkId.ToString());
                ana_dugum.Nodes.Add("Kategori=" +
                                    n.Category.ToString());
                ana_dugum.Nodes.Add("Oluşturulma Zamanı=" +
                                    n.CreatedTime.ToString());
                ana_dugum.Nodes.Add("Bağlantı Zamanı=" +
                                    n.ConnectedTime.ToString());
                ana_dugum.Nodes.Add("Bağlantı Protokolleri=" +
                                    n.Connectivity.ToString());
            }
            treeView1.ExpandAll();
        }
        private IEnumerable <NetworkStatusModel> GetConnectedNetworks()
        {
            var result = NetworkListManager.GetNetworks(NetworkConnectivityLevels.Connected).Select(c => {
                bool?IsConnected = null;
                try {
                    IsConnected = c.IsConnected;
                }
                catch (COMException e)
                {
                    Console.WriteLine(e.Message);
                }
                return(new NetworkStatusModel
                {
                    Name = c.Name,
                    IsConnected = IsConnected
                });
            });

            return(result);
        }
Example #23
0
        /// <summary>
        /// Get the Connection ID for the supplied network
        /// </summary>
        /// <param name="vNetworkID"></param>
        /// <param name="vConnectivityLevels"></param>
        /// <returns></returns>
        public static Guid getConnectionID(Guid vNetworkID, NetworkConnectivityLevels vConnectivityLevels)
        {
            Guid output = new Guid();

            NetworkCollection netCollection = NetworkListManager.GetNetworks(vConnectivityLevels);

            foreach (Network n in netCollection)
            {
                foreach (NetworkConnection c in n.Connections)
                {
                    if (c.Network.NetworkId == n.NetworkId && vNetworkID == c.Network.NetworkId)
                    {
                        output = c.ConnectionId;
                        break;
                    }
                }
            }

            return(output);
        }
        public bool GetNetworkStatus()
        {
            try
            {
                if (activeAdapterIds == null)
                {
                    activeAdapterIds = GetActivePhysicalAdapters();
                }
                var networks = NetworkListManager.GetNetworks(NetworkConnectivityLevels.Connected);
                NetworkInterface[] networkInterfaces = NetworkInterface.GetAllNetworkInterfaces();
                foreach (NetworkInterface netInterface in networkInterfaces)
                {
                    if (netInterface.OperationalStatus == OperationalStatus.Up && netInterface.NetworkInterfaceType != NetworkInterfaceType.Tunnel &&
                        netInterface.NetworkInterfaceType != NetworkInterfaceType.Loopback)
                    {
                        foreach (Microsoft.WindowsAPICodePack.Net.Network network in networks)
                        {
                            foreach (NetworkConnection conn in network.Connections)
                            {
                                string id = netInterface.Id;
                                id = id.Substring(1, id.Length - 2);
                                id = id.ToUpper(CultureInfo.InvariantCulture);

                                if (id.Equals(conn.AdapterId.ToString().ToUpper(CultureInfo.InvariantCulture), StringComparison.InvariantCultureIgnoreCase) &&
                                    activeAdapterIds.Contains(id))
                                {
                                    IsNetworkConnectedToInternet = conn.Network.IsConnectedToInternet;
                                }
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
            }
            return(IsNetworkConnectedToInternet);
        }
        /// <summary>
        /// this method fetches the active connection details
        /// </summary>
        /// <returns>object containing wlaninfo and laninfo</returns>
        private ConnectionInfo GetConnectionDetails()
        {
            ConnectionInfo networkInfo = new ConnectionInfo
            {
                LanInfo  = new LanInfo(),
                WlanInfo = new WlanInfo()
            };

            try
            {
                List <string> adapters = GetActivePhysicalAdapters();
                var           networks = NetworkListManager.GetNetworks(NetworkConnectivityLevels.Connected);
                // fetch all networks adapters that are active and running,
                // adapters which are not loopback or tunnel
                NetworkInterface[] networkInterfaces = NetworkInterface
                                                       .GetAllNetworkInterfaces()
                                                       .Where(ninterface => ninterface.OperationalStatus == OperationalStatus.Up &&
                                                              ninterface.NetworkInterfaceType != NetworkInterfaceType.Tunnel &&
                                                              ninterface.NetworkInterfaceType != NetworkInterfaceType.Loopback)
                                                       .ToArray();
                foreach (NetworkInterface netInterface in networkInterfaces)
                {
                    foreach (Network network in networks)
                    {
                        foreach (NetworkConnection conn in network.Connections)
                        {
                            string id = netInterface.Id;
                            id = id.Substring(1, id.Length - 2);
                            id = id.ToUpper(CultureInfo.InvariantCulture);

                            // compare the adapterid to fetch the right connection name
                            if (id.Equals(conn.AdapterId.ToString().ToUpper(CultureInfo.InvariantCulture), StringComparison.InvariantCultureIgnoreCase) &&
                                adapters.Contains(id))
                            {
                                if (netInterface.NetworkInterfaceType == NetworkInterfaceType.Wireless80211)
                                {
                                    networkInfo.WlanInfo = GetWirelessConnection();
                                    networkInfo.WlanInfo.NetworkCategory = GetNetworkCategory(conn.Network.Category);
                                    if (networkInfo.WlanInfo == null)
                                    {
                                        networkInfo.WlanInfo.SSID      = conn.Network.Name;
                                        networkInfo.WlanInfo.IsSecured = false;
                                    }
                                }
                                else
                                {
                                    networkInfo.LanInfo.Name = conn.Network.Name;
                                }
                            }
                        }
                    }
                }
                return(networkInfo);
            }
#pragma warning disable CA1031 // Do not catch general exception types
            catch (Exception)
#pragma warning restore CA1031 // Do not catch general exception types
            {
                return(networkInfo);
            }
        }
Example #26
0
        private void repairFirewall()
        {
            if (Environment.OSVersion.Platform == PlatformID.Win32NT && Environment.OSVersion.Version.Major == 5 && Environment.OSVersion.Version.Minor == 1)
            {
                // windows XP. Can't do this, yo.
            }
            else
            {
                authorizeChromeApplication();

                var manager           = new NetworkListManager();
                var connectedNetworks = manager.GetNetworks(NLM_ENUM_NETWORK.NLM_ENUM_NETWORK_CONNECTED).Cast <INetwork>();
                foreach (var network in connectedNetworks)
                {
                    Console.Write(network.GetName() + " ");
                    var cat = network.GetCategory();
                    if (cat == NLM_NETWORK_CATEGORY.NLM_NETWORK_CATEGORY_PRIVATE)
                    {
                        Console.WriteLine("[PRIVATE]");
                        network.SetCategory(NLM_NETWORK_CATEGORY.NLM_NETWORK_CATEGORY_PUBLIC);
                    }
                    else if (cat == NLM_NETWORK_CATEGORY.NLM_NETWORK_CATEGORY_PUBLIC)
                    {
                        Console.WriteLine("[PUBLIC]");
                        //network.SetCategory(NLM_NETWORK_CATEGORY.NLM_NETWORK_CATEGORY_PRIVATE);
                    }
                    else if (cat == NLM_NETWORK_CATEGORY.NLM_NETWORK_CATEGORY_DOMAIN_AUTHENTICATED)
                    {
                        Console.WriteLine("[DOMAIN]");
                    }
                }

                try
                {
                    ArrayList list = (ArrayList)FirewallHelper.Instance.GetAuthorizedAppPaths();
                    foreach (string[] item in list)
                    {
                        String appName = item[0];
                        String appPath = item[1];
                        if (appName != null && appName.Equals("Google Chrome"))
                        {
                            FirewallHelper.Instance.GrantAuthorization(appPath, appName);
                        }
                    }
                }
                catch (Exception ex)
                {
                    // Didn't work. Meh.
                }

                try
                {
                    INetFwPolicy2 fwPolicy2;
                    Type          tNetFwPolicy2 = Type.GetTypeFromProgID("HNetCfg.FwPolicy2");
                    fwPolicy2 = (INetFwPolicy2)Activator.CreateInstance(tNetFwPolicy2);
                    fwPolicy2.set_BlockAllInboundTraffic(NET_FW_PROFILE_TYPE2_.NET_FW_PROFILE2_PRIVATE, false);
                    //fwPolicy2.set_DefaultInboundAction(NET_FW_PROFILE_TYPE2_.NET_FW_PROFILE2_PRIVATE, NET_FW_ACTION_.NET_FW_ACTION_ALLOW);
                }
                catch (Exception ex)
                {
                }
            }
            this.openPort(5556, "Videostream Desktop Application");
            this.openPort(5558, "Videostream Mobile Application");
        }
Example #27
0
        public Dictionary <string, List <string> > NetworksByProfileDict(NET_FW_PROFILE_TYPE2_ profile, NetworkConnectivityLevels level = NetworkConnectivityLevels.All)
        {
            var networks = new Dictionary <string, List <string> >();

            //populate interface lookup
            var adapterLookup = new Dictionary <string, string>();

            NetworkInterface[] adapters = NetworkInterface.GetAllNetworkInterfaces();
            foreach (NetworkInterface adapter in adapters)
            {
                //from:{E46DFF2D-EB92-4A84-A0D3-01DDD2DC041E}
                //  to: e46dff2d-eb92-4a84-a0d3-01ddd2dc041e
                logger.Debug("Adapter: {0}={1}", adapter.Id.ToLower().Replace("{", "").Replace("}", ""), adapter.Name);
                adapterLookup.Add(adapter.Id.ToLower().Replace("{", "").Replace("}", ""), adapter.Name);
            }

            NetworkCategory profileName = NetworkCategory.Public;

            switch (profile)
            {
            case NET_FW_PROFILE_TYPE2_.NET_FW_PROFILE2_DOMAIN:
                profileName = NetworkCategory.Authenticated;
                break;

            case NET_FW_PROFILE_TYPE2_.NET_FW_PROFILE2_PRIVATE:
                profileName = NetworkCategory.Private;
                break;

            case NET_FW_PROFILE_TYPE2_.NET_FW_PROFILE2_PUBLIC:
                profileName = NetworkCategory.Public;
                break;
            }

            /*
             * NetworkCollection nCollection2 = NetworkListManager.GetNetworks(NetworkConnectivityLevels.All);
             * foreach (Network net in nCollection2)
             * {
             *  if (net.IsConnected || net.IsConnectedToInternet)
             *  {
             *      Console.WriteLine(String.Format("CONNECTED: {0} {1} {2} {3}", net.Name, net.Category, net.DomainType, net.IsConnectedToInternet));
             *  }
             *  else
             *  {
             *      Console.WriteLine(String.Format("Not connected: {0} {1} {2} {3}", net.Name, net.Category, net.DomainType, net.IsConnectedToInternet));
             *  }
             * }
             */

            //Install-Package WindowsAPICodePack-Core
            NetworkCollection nCollection = NetworkListManager.GetNetworks(level);

            foreach (Network net in nCollection)
            {
                logger.Debug("Network: {0}={1}", net.Name, net.Category);
                if (net.Category == profileName)
                {
                    var netAdapters = new List <string>();
                    var conns       = net.Connections;
                    if (conns.Count() == 0)
                    {
                        logger.Debug("No active connections for network");
                    }
                    foreach (var c in conns)
                    {
                        if (adapterLookup.ContainsKey(c.AdapterId.ToString()))
                        {
                            logger.Debug("Found adapter: {0}", adapterLookup[c.AdapterId.ToString()]);
                            netAdapters.Add(adapterLookup[c.AdapterId.ToString()]);
                        }
                        else
                        {
                            logger.Debug("Unknown adapter: {0}", c.AdapterId.ToString());
                            netAdapters.Add("Unknown");
                        }
                    }

                    networks.Add(net.Name, new List <string>());
                    foreach (var na in netAdapters)
                    {
                        networks[net.Name].Add(na);
                    }
                }
            }
            return(networks);
        }
Example #28
0
 private static string[] QueryNetworks()
 {
     return(NetworkListManager.GetNetworks(NetworkConnectivityLevels.Connected).Select(network => network.Name).ToArray());
 }