Example #1
0
        private void UpdateTCPStats(NetworkInterfaceComponent version)
        {
            IPGlobalProperties ipgp = IPGlobalProperties.GetIPGlobalProperties();
            TcpStatistics      tcpstat;

            if (version == NetworkInterfaceComponent.IPv4)
            {
                tcpstat = ipgp.GetTcpIPv4Statistics();
            }
            else
            {
                tcpstat = ipgp.GetTcpIPv6Statistics();
            }

            txtConnectionsAccepted.Text      = tcpstat.ConnectionsAccepted.ToString("n", nfi);
            txtConnectionsInitiated.Text     = tcpstat.ConnectionsInitiated.ToString("n", nfi);
            txtCumulativeConnections.Text    = tcpstat.CumulativeConnections.ToString("n", nfi);
            txtCurrentConnections.Text       = tcpstat.CurrentConnections.ToString("n", nfi);
            txtFailedConnectionAttempts.Text = tcpstat.FailedConnectionAttempts.ToString("n", nfi);
            txtMaximumConnections.Text       = tcpstat.MaximumConnections.ToString("n", nfi);
            txtResetConnections.Text         = tcpstat.ResetConnections.ToString("n", nfi);

            txtErrorsReceived.Text = tcpstat.ErrorsReceived.ToString("n", nfi);

            txtMaximumTransmissionTimeout.Text = String.Format("{0} ms", tcpstat.MaximumTransmissionTimeout.ToString("n", nfi));
            txtMinimumTransmissionTimeout.Text = String.Format("{0} ms", tcpstat.MinimumTransmissionTimeout.ToString("n", nfi));
            txtResetsSent.Text       = tcpstat.ResetsSent.ToString("n", nfi);
            txtSegmentsReceived.Text = tcpstat.SegmentsReceived.ToString("n", nfi);
            txtSegmentsResent.Text   = tcpstat.SegmentsResent.ToString("n", nfi);
            txtSegmentsSent.Text     = tcpstat.SegmentsSent.ToString("n", nfi);
        }
Example #2
0
        private void UpdateUDPStats(NetworkInterfaceComponent version)
        {
            try
            {
                IPGlobalProperties ipgp = IPGlobalProperties.GetIPGlobalProperties();
                UdpStatistics      udpstat;

                if (version == NetworkInterfaceComponent.IPv4)
                {
                    udpstat = ipgp.GetUdpIPv4Statistics();
                }
                else
                {
                    udpstat = ipgp.GetUdpIPv6Statistics();
                }

                txtDatagramsReceived.Text           = udpstat.DatagramsReceived.ToString("n", nfi);
                txtDatagramsSent.Text               = udpstat.DatagramsSent.ToString("n", nfi);
                txtIncomingDatagramsDiscarded.Text  = udpstat.IncomingDatagramsDiscarded.ToString("n", nfi);
                txtIncomingDatagramsWithErrors.Text = udpstat.IncomingDatagramsWithErrors.ToString("n", nfi);
                txtUdpListeners.Text = udpstat.UdpListeners.ToString("n", nfi);
            }
            catch (NetworkInformationException) { }
            catch (PlatformNotSupportedException) { }
            catch (FormatException) { }
        }
        /// <summary>
        ///     Get the nameservers of an interface.
        /// </summary>
        /// <param name="localNetworkInterface">The interface to extract from.</param>
        /// <param name="networkInterfaceComponent">IPv4 or IPv6.</param>
        /// <returns>A list of nameservers.</returns>
        internal static List <string> GetDnsServerList(string localNetworkInterface,
                                                       NetworkInterfaceComponent networkInterfaceComponent)
        {
            var serverAddresses = new List <string>();

            try
            {
                var registryKey = networkInterfaceComponent == NetworkInterfaceComponent.IPv6
                                        ? Registry.GetValue(
                    "HKEY_LOCAL_MACHINE\\SYSTEM\\CurrentControlSet\\Services\\TCPIP6\\Parameters\\Interfaces\\" +
                    localNetworkInterface,
                    "NameServer", "")
                                        : Registry.GetValue(
                    "HKEY_LOCAL_MACHINE\\SYSTEM\\CurrentControlSet\\Services\\Tcpip\\Parameters\\Interfaces\\" +
                    localNetworkInterface,
                    "NameServer", "");

                if (registryKey != null && registryKey.ToString().Length > 0)
                {
                    serverAddresses =
                        new List <string>(((string)registryKey).Split(new[] { "," }, StringSplitOptions.None));
                }
            }
            catch (Exception)
            {
            }
            return(serverAddresses);
        }
Example #4
0
        //</Snippet2>


        //<Snippet3>
        public static void ShowUdpStatistics(NetworkInterfaceComponent version)
        {
            IPGlobalProperties properties = IPGlobalProperties.GetIPGlobalProperties();
            UdpStatistics      udpStat    = null;

            switch (version)
            {
            case NetworkInterfaceComponent.IPv4:
                udpStat = properties.GetUdpIPv4Statistics();
                Console.WriteLine("UDP IPv4 Statistics");
                break;

            case NetworkInterfaceComponent.IPv6:
                udpStat = properties.GetUdpIPv6Statistics();
                Console.WriteLine("UDP IPv6 Statistics");
                break;

            default:
                throw new ArgumentException("version");
                //    break;
            }
            Console.WriteLine("  Datagrams Received ...................... : {0}",
                              udpStat.DatagramsReceived);
            Console.WriteLine("  Datagrams Sent .......................... : {0}",
                              udpStat.DatagramsSent);
            Console.WriteLine("  Incoming Datagrams Discarded ............ : {0}",
                              udpStat.IncomingDatagramsDiscarded);
            Console.WriteLine("  Incoming Datagrams With Errors .......... : {0}",
                              udpStat.IncomingDatagramsWithErrors);
            Console.WriteLine("  UDP Listeners ........................... : {0}",
                              udpStat.UdpListeners);
            Console.WriteLine("");
        }
Example #5
0
        private string GetUdpStatistics(
            NetworkInterfaceComponent version,
            IPGlobalProperties properties)
        {
            UdpStatistics udpStat = null;

            StringBuilder udpStatBuilder = new StringBuilder();

            try
            {
                switch (version)
                {
                case NetworkInterfaceComponent.IPv4:
                    udpStat = properties.GetUdpIPv4Statistics();
                    udpStatBuilder.Append("UDP IPv4 Statistics\n");
                    break;

                case NetworkInterfaceComponent.IPv6:
                    udpStat = properties.GetUdpIPv6Statistics();
                    udpStatBuilder.Append("UDP IPv6 Statistics\n");
                    break;

                default:
                    throw new ArgumentException("No such IP version");
                }
            }
            catch (NetworkInformationException)
            {
                return(String.Empty);
            }

            udpStatBuilder.Append("=================================================\n");

            udpStatBuilder.AppendFormat(" Datagrams Received ............ : {0}\n",
                                        udpStat.DatagramsReceived);
            udpStatBuilder.AppendFormat(" Datagrams Sent ................ : {0}\n",
                                        udpStat.DatagramsSent);
            udpStatBuilder.AppendFormat(" Incoming Datagrams Discarded .. : {0}\n",
                                        udpStat.IncomingDatagramsDiscarded);
            udpStatBuilder.AppendFormat(" Incoming Datagrams With Errors  : {0}\n",
                                        udpStat.IncomingDatagramsWithErrors);
            udpStatBuilder.AppendFormat(" UDP Listeners ................. : {0}\n",
                                        udpStat.UdpListeners);

            IPEndPoint[] endPoints = properties.GetActiveUdpListeners();

            if (endPoints.Length > 0)
            {
                udpStatBuilder.Append("  Local Address   Port\n");
            }

            foreach (IPEndPoint endPoint in endPoints)
            {
                udpStatBuilder.AppendFormat("  {0, -15}:{1}\n",
                                            endPoint.Address, endPoint.Port);
            }

            return(udpStatBuilder.ToString());
        }
 public override bool Supports(NetworkInterfaceComponent networkInterfaceComponent)
 {
     if (networkInterfaceComponent != NetworkInterfaceComponent.IPv4)
     {
         return(networkInterfaceComponent == NetworkInterfaceComponent.IPv6 && this.mib6.Index >= 0);
     }
     return(this.mib4.Index >= 0);
 }
Example #7
0
        public override bool Supports(NetworkInterfaceComponent networkInterfaceComponent)
        {
            Sockets.AddressFamily family =
                (networkInterfaceComponent == NetworkInterfaceComponent.IPv4)
                ? Sockets.AddressFamily.InterNetwork
                : Sockets.AddressFamily.InterNetworkV6;

            return(_addresses.Any(addr => addr.AddressFamily == family));
        }
        public override bool Supports(NetworkInterfaceComponent networkInterfaceComponent)
        {
            Sockets.AddressFamily family =
                (networkInterfaceComponent == NetworkInterfaceComponent.IPv4)
                ? Sockets.AddressFamily.InterNetwork
                : Sockets.AddressFamily.InterNetworkV6;

            return _addresses.Any(addr => addr.AddressFamily == family);
        }
Example #9
0
        private void UpdateGlobalStats(NetworkInterfaceComponent version)
        {
            IPGlobalProperties ipgp = IPGlobalProperties.GetIPGlobalProperties();
            IPGlobalStatistics ipgs;



            if (version == NetworkInterfaceComponent.IPv4)
            {
                ipgs = ipgp.GetIPv4GlobalStatistics();
            }
            else
            {
                try
                {
                    ipgs = ipgp.GetIPv6GlobalStatistics();
                }
                catch
                {
                    ipgs = ipgp.GetIPv4GlobalStatistics();
                }
            }

            txtDhcpScopeName.Text = ipgp.DhcpScopeName;
            txtDomainName.Text    = ipgp.DomainName;
            txtHostName.Text      = ipgp.HostName;
            txtIsWinsProxy.Text   = ipgp.IsWinsProxy ? Res.str_Yes : Res.str_No;
            txtNodeType.Text      = ipgp.NodeType.ToString();

            txtDefaultTTL.Text          = String.Format("{0} hops", ipgs.DefaultTtl);
            txtForwardingEnabled.Text   = ipgs.ForwardingEnabled ? Res.str_Yes : Res.str_No;
            txtNumberOfInterfaces.Text  = ipgs.NumberOfInterfaces.ToString("n", nfi);
            txtNumberOfIPAddresses.Text = ipgs.NumberOfIPAddresses.ToString("n", nfi);
            txtNumberOfRoutes.Text      = ipgs.NumberOfRoutes.ToString("n", nfi);

            txtOutputPacketRequests.Text        = ipgs.OutputPacketRequests.ToString("n", nfi);
            txtOutputPacketRoutingDiscards.Text = ipgs.OutputPacketRoutingDiscards.ToString("n", nfi);
            txtOutputPacketsDiscarded.Text      = ipgs.OutputPacketsDiscarded.ToString("n", nfi);
            txtOutputPacketsWithNoRoute.Text    = ipgs.OutputPacketsWithNoRoute.ToString("n", nfi);

            txtPacketFragmentFailures.Text     = ipgs.PacketFragmentFailures.ToString("n", nfi);
            txtPacketReassembliesRequired.Text = ipgs.PacketReassembliesRequired.ToString("n", nfi);
            txtPacketReassemblyFailures.Text   = ipgs.PacketReassemblyFailures.ToString("n", nfi);
            txtPacketReassemblyTimeout.Text    = String.Format("{0} ms", ipgs.PacketReassemblyTimeout.ToString("n", nfi));
            txtPacketsFragmented.Text          = ipgs.PacketsFragmented.ToString("n", nfi);
            txtPacketsReassembled.Text         = ipgs.PacketsReassembled.ToString("n", nfi);

            txtReceivedPackets.Text                    = ipgs.ReceivedPackets.ToString("n", nfi);
            txtReceivedPacketsDelivered.Text           = ipgs.ReceivedPacketsDelivered.ToString("n", nfi);
            txtReceivedPacketsDiscarded.Text           = ipgs.ReceivedPacketsDiscarded.ToString("n", nfi);
            txtReceivedPacketsForwarded.Text           = ipgs.ReceivedPacketsForwarded.ToString("n", nfi);
            txtReceivedPacketsWithAddressErrors.Text   = ipgs.ReceivedPacketsWithAddressErrors.ToString("n", nfi);
            txtReceivedPacketsWithHeadersErrors.Text   = ipgs.ReceivedPacketsWithHeadersErrors.ToString("n", nfi);
            txtReceivedPacketsWithUnknownProtocol.Text = ipgs.ReceivedPacketsWithUnknownProtocol.ToString("n", nfi);
        }
Example #10
0
        //</Snippet1>

        //<Snippet2>
        public static void ShowTcpStatistics(NetworkInterfaceComponent version)
        {
            //<Snippet21>
            IPGlobalProperties properties = IPGlobalProperties.GetIPGlobalProperties();
            TcpStatistics      tcpstat    = null;

            Console.WriteLine("");
            switch (version)
            {
            case NetworkInterfaceComponent.IPv4:
                tcpstat = properties.GetTcpIPv4Statistics();
                Console.WriteLine("TCP/IPv4 Statistics:");
                break;

            case NetworkInterfaceComponent.IPv6:
                tcpstat = properties.GetTcpIPv6Statistics();
                Console.WriteLine("TCP/IPv6 Statistics:");
                break;

            default:
                throw new ArgumentException("version");
                //    break;
            }
            //</Snippet21>
            Console.WriteLine("  Minimum Transmission Timeout............. : {0}",
                              tcpstat.MinimumTransmissionTimeout);
            Console.WriteLine("  Maximum Transmission Timeout............. : {0}",
                              tcpstat.MaximumTransmissionTimeout);

            Console.WriteLine("  Connection Data:");
            Console.WriteLine("      Current  ............................ : {0}",
                              tcpstat.CurrentConnections);
            Console.WriteLine("      Cumulative .......................... : {0}",
                              tcpstat.CumulativeConnections);
            Console.WriteLine("      Initiated ........................... : {0}",
                              tcpstat.ConnectionsInitiated);
            Console.WriteLine("      Accepted ............................ : {0}",
                              tcpstat.ConnectionsAccepted);
            Console.WriteLine("      Failed Attempts ..................... : {0}",
                              tcpstat.FailedConnectionAttempts);
            Console.WriteLine("      Reset ............................... : {0}",
                              tcpstat.ResetConnections);

            Console.WriteLine("");
            Console.WriteLine("  Segment Data:");
            Console.WriteLine("      Received  ........................... : {0}",
                              tcpstat.SegmentsReceived);
            Console.WriteLine("      Sent ................................ : {0}",
                              tcpstat.SegmentsSent);
            Console.WriteLine("      Retransmitted ....................... : {0}",
                              tcpstat.SegmentsResent);

            Console.WriteLine("");
        }
Example #11
0
        public override bool Supports(NetworkInterfaceComponent networkInterfaceComponent)
        {
            switch (networkInterfaceComponent)
            {
            case NetworkInterfaceComponent.IPv4:
                return(mib4.Index >= 0);

            case NetworkInterfaceComponent.IPv6:
                return(mib6.Index >= 0);
            }
            return(false);
        }
        /// <summary>
        ///     Set's the IPv4 or IPv6 DNS Servers of an interface.
        /// </summary>
        /// <param name="localNetworkInterface">The interface to work with.</param>
        /// <param name="dnsServers">List of dns servers to set.</param>
        /// <param name="networkInterfaceComponent">IPv4 or IPv6.</param>
        public static void SetNameservers(LocalNetworkInterface localNetworkInterface, List<string> dnsServers,
            NetworkInterfaceComponent networkInterfaceComponent = NetworkInterfaceComponent.IPv4)
        {
            if (networkInterfaceComponent == NetworkInterfaceComponent.IPv4)
            {
                using (var networkConfigMng = new ManagementClass("Win32_NetworkAdapterConfiguration"))
                {
                    using (var networkConfigs = networkConfigMng.GetInstances())
                    {
                        foreach (
                            var managementObject in
                                networkConfigs.Cast<ManagementObject>()
                                    .Where(
                                        mo =>
                                            (bool) mo["IPEnabled"] &&
                                            (string) mo["Description"] == localNetworkInterface.Description))
                        {
                            using (var newDns = managementObject.GetMethodParameters("SetDNSServerSearchOrder"))
                            {
                                newDns["DNSServerSearchOrder"] = dnsServers.ToArray();
                                managementObject.InvokeMethod("SetDNSServerSearchOrder", newDns, null);
                            }
                        }
                    }
                }
            }
            else
            {
                //TODO: find better way to set IPv6 nameservers
                using (var process = new Process())
                {
                    var processStartInfo = new ProcessStartInfo("netsh",
                        "interface ipv6 delete dns \"" + localNetworkInterface.Name + "\" all")
                    {
                        WindowStyle = ProcessWindowStyle.Minimized
                    };
                    process.StartInfo = processStartInfo;
                    process.Start();

                    foreach (var address in dnsServers)
                    {
                        //netsh interface ipv6 add dns "Interface Name" 127.0.0.1 validate=no
                        processStartInfo = new ProcessStartInfo("netsh",
                            "interface ipv6 add dns \"" + localNetworkInterface.Name + "\" " + address + " validate=no")
                        {
                            WindowStyle = ProcessWindowStyle.Minimized
                        };
                        process.StartInfo = processStartInfo;
                        process.Start();
                    }
                }
            }
        }
Example #13
0
        public override bool Supports(NetworkInterfaceComponent networkInterfaceComponent)
        {
            switch (networkInterfaceComponent)
            {
            case NetworkInterfaceComponent.IPv4:
                return(Directory.Exists("/proc/sys/net/ipv4/conf/" + iface));

            case NetworkInterfaceComponent.IPv6:
                return(Directory.Exists("/proc/sys/net/ipv6/conf/" + iface));
            }
            return(false);
        }
Example #14
0
        public static void DisplayTcpStatistics(NetworkInterfaceComponent version, TextWriter outputStream)
        {
            IPGlobalProperties properties =
                IPGlobalProperties.GetIPGlobalProperties();
            TcpStatistics tcpstat = null;

            outputStream.WriteLine("");
            switch (version)
            {
            case NetworkInterfaceComponent.IPv4:
                tcpstat = properties.GetTcpIPv4Statistics();
                outputStream.WriteLine("TCP/IPv4 Statistics:");
                break;

            case NetworkInterfaceComponent.IPv6:
                tcpstat = properties.GetTcpIPv6Statistics();
                outputStream.WriteLine("TCP/IPv6 Statistics:");
                break;

            default:
                throw new ArgumentException("version");
            }
            outputStream.WriteLine("  Minimum Transmission Timeout. : {0}",
                                   tcpstat.MinimumTransmissionTimeout);
            outputStream.WriteLine("  Maximum Transmission Timeout : {0}",
                                   tcpstat.MaximumTransmissionTimeout);

            outputStream.WriteLine(" Connection Data:");
            outputStream.WriteLine("      Current : {0}",
                                   tcpstat.CurrentConnections);
            outputStream.WriteLine("      Cumulative : {0}",
                                   tcpstat.CumulativeConnections);
            outputStream.WriteLine("      Initiated : {0}",
                                   tcpstat.ConnectionsInitiated);
            outputStream.WriteLine("      Accepted : {0}",
                                   tcpstat.ConnectionsAccepted);
            outputStream.WriteLine("      Failed Attempts : {0}",
                                   tcpstat.FailedConnectionAttempts);
            outputStream.WriteLine("      Reset : {0}",
                                   tcpstat.ResetConnections);

            outputStream.WriteLine("");
            outputStream.WriteLine("  Segment Data:");
            outputStream.WriteLine("      Received  ................... : {0}",
                                   tcpstat.SegmentsReceived);
            outputStream.WriteLine("      Sent : {0}",
                                   tcpstat.SegmentsSent);
            outputStream.WriteLine("      Retransmitted : {0}",
                                   tcpstat.SegmentsResent);

            outputStream.WriteLine("");
        }
 public override bool Supports(NetworkInterfaceComponent networkInterfaceComponent)
 {
     if (networkInterfaceComponent == NetworkInterfaceComponent.IPv6 &&
         ((adapterFlags & AdapterFlags.IPv6Enabled) != 0))
     {
         return(true);
     }
     if (networkInterfaceComponent == NetworkInterfaceComponent.IPv4 &&
         ((adapterFlags & AdapterFlags.IPv4Enabled) != 0))
     {
         return(true);
     }
     return(false);
 }
Example #16
0
        public override bool Supports(NetworkInterfaceComponent networkInterfaceComponent)
        {
            Sockets.AddressFamily family = (networkInterfaceComponent == NetworkInterfaceComponent.IPv4) ?
                                           Sockets.AddressFamily.InterNetwork :
                                           Sockets.AddressFamily.InterNetworkV6;

            foreach (UnixUnicastIPAddressInformation addr in _unicastAddresses)
            {
                if (addr.Address.AddressFamily == family)
                {
                    return(true);
                }
            }

            return(false);
        }
Example #17
0
        /// <summary>
        /// Gets the TCP statistics for a given network interface component
        /// </summary>
        public static TcpStatistics GetTcpStatistics(NetworkInterfaceComponent version)
        {
            var properties = IPGlobalProperties.GetIPGlobalProperties();

            switch (version)
            {
            case NetworkInterfaceComponent.IPv4:
                return(properties.GetTcpIPv4Statistics());

            case NetworkInterfaceComponent.IPv6:
                return(properties.GetTcpIPv6Statistics());

            default:
                throw new ArgumentException("version");
            }
        }
Example #18
0
        /*private void ReEnableControlsInTabPage(TabPage tab, bool enable = true)
         * {
         *  foreach (Control ctrl in tab.Controls)
         *  {
         *      ctrl.Enabled = enable;
         *      if (ctrl.GetType().Name == "GroupBox")
         *      {
         *          foreach (Control child in ((GroupBox)ctrl).Controls)
         *          {
         *              child.Enabled = enable;
         *          }
         *      }
         *  }
         * }*/

        private void radioButtonIPv4_CheckedChanged(object sender, EventArgs e)
        {
            if (radioButtonIPv4.Checked)
            {
                ProtocolVersion = NetworkInterfaceComponent.IPv4;

                //tabPageICMPv4.Enabled = true;
                //tabPageICMPv6.Enabled = false;
            }
            else
            {
                ProtocolVersion = NetworkInterfaceComponent.IPv6;

                //tabPageICMPv4.Enabled = false;
                //tabPageICMPv6.Enabled = true;
            }
        }
        public override bool Supports(NetworkInterfaceComponent networkInterfaceComponent)
        {
            bool flag  = networkInterfaceComponent == NetworkInterfaceComponent.IPv4;
            bool flag2 = !flag && networkInterfaceComponent == NetworkInterfaceComponent.IPv6;

            foreach (IPAddress address in addresses)
            {
                if (flag && address.AddressFamily == AddressFamily.InterNetwork)
                {
                    return(true);
                }
                if (flag2 && address.AddressFamily == AddressFamily.InterNetworkV6)
                {
                    return(true);
                }
            }
            return(false);
        }
Example #20
0
        /// <summary>
        /// Whether this NIC support the networkInterfaceComponent (ipv4, ipv6 etc)
        /// </summary>
        /// <param name="networkInterfaceComponent"></param>
        /// <returns>return true if any IP Address support, otherwise false</returns>
        public override bool Supports(NetworkInterfaceComponent networkInterfaceComponent)
        {
            AddressFamily family = AddressFamily.InterNetwork;

            if (networkInterfaceComponent == NetworkInterfaceComponent.IPv6)
            {
                family = AddressFamily.InterNetworkV6;
            }
            UnicastIPAddressInformationCollection uniIpInfoColl = properties.UnicastAddresses;

            foreach (MockIPAddressInformation item in uniIpInfoColl)
            {
                if (item.Address.AddressFamily == family)
                {
                    return(true);
                }
            }
            return(false);
        }
Example #21
0
        public override bool Supports(NetworkInterfaceComponent networkInterfaceComponent)
        {
            bool wantIPv4 = networkInterfaceComponent == NetworkInterfaceComponent.IPv4;
            bool wantIPv6 = wantIPv4 ? false : networkInterfaceComponent == NetworkInterfaceComponent.IPv6;

            foreach (IPAddress address in addresses)
            {
                if (wantIPv4 && address.AddressFamily == AddressFamily.InterNetwork)
                {
                    return(true);
                }
                else if (wantIPv6 && address.AddressFamily == AddressFamily.InterNetworkV6)
                {
                    return(true);
                }
            }

            return(false);
        }
Example #22
0
        /// <summary>
        /// Used to construct a primitive IpPacket object with the intention to encode it for transmission on the network.
        /// </summary>
        /// <param name="IpVersion">IP version</param>
        /// <param name="InternetHeaderLength">IP header length</param>
        /// <param name="DscpValue">DSCP value to encode</param>
        /// <param name="ExplicitCongestionNotice">ECN value to encode</param>
        /// <param name="IpPacketLength">Length of the complete packet</param>
        /// <param name="FragmentGroupId">Fragement ID, may be 0</param>
        /// <param name="IpHeaderFlags">Header flags</param>
        /// <param name="FragmentOffset">Fragment offset, may be 0</param>
        /// <param name="TimeToLive">Internet TTL</param>
        /// <param name="Protocol">Protocol Type</param>
        /// <param name="SourceIpAddress">Source IPAddress, not assumed to be on the local host.</param>
        /// <param name="DestinationIpAddress">Destination IPAddress</param>
        /// <param name="IpOptions">IPOptions in Byte[] form</param>
        /// <param name="PacketData">The remainder of the packet.</param>
        /// <remarks>Note that the IP Header checksum would be computed when the ToWireBytes() method is called.</remarks>
        public IpPacket(
            NetworkInterfaceComponent IpVersion,
            byte InternetHeaderLength,
            byte DscpValue,
            byte ExplicitCongestionNotice,
            ushort IpPacketLength,
            ushort FragmentGroupId,
            byte IpHeaderFlags,
            ushort FragmentOffset,
            byte TimeToLive,
            ProtocolType Protocol,

            IPAddress SourceIpAddress,
            IPAddress DestinationIpAddress,
            byte[] IpOptions,
            byte[] PacketData
            )
        {
            this.IpVersion                = IpVersion;
            this.InternetHeaderLength     = InternetHeaderLength;
            this.DscpValue                = DscpValue;
            this.ExplicitCongestionNotice = ExplicitCongestionNotice;
            this.IpPacketLength           = IpPacketLength;
            this.FragmentGroupId          = FragmentGroupId;
            this.IpHeaderFlags            = IpHeaderFlags;
            this.FragmentOffset           = FragmentOffset;
            this.TimeToLive               = TimeToLive;
            this.Protocol             = Protocol;
            this.ProtocolNumber       = (byte)Protocol;
            this.PacketHeaderChecksum = 0; //set to zero for new packet
            this.SourceIpAddress      = SourceIpAddress;
            this.DestinationIpAddress = DestinationIpAddress;
            this.IpOptions            = new byte[IpOptions.Length];
            Array.Copy(IpOptions, this.IpOptions, IpOptions.Length);
            this.PacketData = new byte[PacketData.Length];
            Array.Copy(PacketData, this.PacketData, PacketData.Length);
        }
Example #23
0
 /// <summary>
 /// Used to construct a primitive IpPacket object with the intention to encode it for transmission on the network.
 /// </summary>
 /// <param name="IpVersion">IP version</param>
 /// <param name="InternetHeaderLength">IP header length</param>
 /// <param name="DscpValue">DSCP value to encode</param>
 /// <param name="ExplicitCongestionNotice">ECN value to encode</param>
 /// <param name="IpPacketLength">Length of the complete packet</param>
 /// <param name="FragmentGroupId">Fragement ID, may be 0</param>
 /// <param name="IpHeaderFlags">Header flags</param>
 /// <param name="FragmentOffset">Fragment offset, may be 0</param>
 /// <param name="TimeToLive">Internet TTL</param>
 /// <param name="Protocol">Protocol Type</param>
 /// <param name="SourceIpAddress">Source IPAddress, not assumed to be on the local host.</param>
 /// <param name="DestinationIpAddress">Destination IPAddress</param>
 /// <param name="IpOptions">IPOptions in Byte[] form</param>
 /// <param name="PacketData">The remainder of the packet.</param>
 /// <remarks>Note that the IP Header checksum would be computed when the ToWireBytes() method is called.</remarks>
 public IpPacket(
      NetworkInterfaceComponent IpVersion,
      byte InternetHeaderLength,
      byte DscpValue,
      byte ExplicitCongestionNotice,
      ushort IpPacketLength,
      ushort FragmentGroupId,
      byte IpHeaderFlags,
      ushort FragmentOffset,
      byte TimeToLive,
      ProtocolType Protocol,
      
      IPAddress SourceIpAddress,
      IPAddress DestinationIpAddress,
      byte[] IpOptions,
      byte[] PacketData
     )
 {
     this.IpVersion = IpVersion;
     this.InternetHeaderLength = InternetHeaderLength;
     this.DscpValue = DscpValue;
     this.ExplicitCongestionNotice = ExplicitCongestionNotice;
     this.IpPacketLength = IpPacketLength;
     this.FragmentGroupId = FragmentGroupId;
     this.IpHeaderFlags = IpHeaderFlags;
     this.FragmentOffset = FragmentOffset;
     this.TimeToLive = TimeToLive;
     this.Protocol = Protocol;
     this.ProtocolNumber = (byte)Protocol;
     this.PacketHeaderChecksum = 0; //set to zero for new packet
     this.SourceIpAddress = SourceIpAddress;
     this.DestinationIpAddress = DestinationIpAddress;
     this.IpOptions = new byte[IpOptions.Length];
     Array.Copy(IpOptions, this.IpOptions, IpOptions.Length);
     this.PacketData = new byte[PacketData.Length];
     Array.Copy(PacketData, this.PacketData, PacketData.Length);
 }
Example #24
0
        public override bool Supports(NetworkInterfaceComponent networkInterfaceComponent)
        {
            if (networkInterfaceComponent == NetworkInterfaceComponent.IPv6
                && ((_adapterFlags & Interop.IpHlpApi.AdapterFlags.IPv6Enabled) != 0))
            {
                return true;
            }

            if (networkInterfaceComponent == NetworkInterfaceComponent.IPv4
                && ((_adapterFlags & Interop.IpHlpApi.AdapterFlags.IPv4Enabled) != 0))
            {
                return true;
            }

            return false;
        }
Example #25
0
 public virtual bool Supports(NetworkInterfaceComponent networkInterfaceComponent)
 {
     throw NotImplemented.ByDesignWithMessage(SR.net_MethodNotImplementedException);
 }
 public override bool Supports(NetworkInterfaceComponent networkInterfaceComponent)
 {
     throw NotImplemented.ByDesign;
 }
Example #27
0
		public override bool Supports (NetworkInterfaceComponent networkInterfaceComponent)
		{
			bool wantIPv4 = networkInterfaceComponent == NetworkInterfaceComponent.IPv4;
			bool wantIPv6 = wantIPv4 ? false : networkInterfaceComponent == NetworkInterfaceComponent.IPv6;
				
			foreach (IPAddress address in addresses) {
				if (wantIPv4 && address.AddressFamily == AddressFamily.InterNetwork)
					return true;
				else if (wantIPv6 && address.AddressFamily == AddressFamily.InterNetworkV6)
					return true;
			}
			
			return false;
		}
 public virtual bool Supports(NetworkInterfaceComponent networkInterfaceComponent) {
     throw new NotImplementedException();
 }
 public override bool Supports(NetworkInterfaceComponent networkInterfaceComponent)
 {
     return (((networkInterfaceComponent == NetworkInterfaceComponent.IPv6) && (this.ipv6Index > 0)) || ((networkInterfaceComponent == NetworkInterfaceComponent.IPv4) && (this.index > 0)));
 }
        private string GetTcpStatistics(
            NetworkInterfaceComponent version,
            IPGlobalProperties properties)
        {
            TcpStatistics tcpStat = null;

            StringBuilder tcpStatBuilder = new StringBuilder();

            try
            {
                switch (version)
                {
                    case NetworkInterfaceComponent.IPv4:
                        tcpStat = properties.GetTcpIPv4Statistics();
                        tcpStatBuilder.Append("TCP/IPv4 Statistics\n");
                        break;
                    case NetworkInterfaceComponent.IPv6:
                        tcpStat = properties.GetTcpIPv6Statistics();
                        tcpStatBuilder.Append("TCP/IPv6 Statistics\n");
                        break;
                    default:
                        throw new ArgumentException("No such IP version");

                }
            }
            catch (NetworkInformationException)
            {
                return String.Empty;
            }

            tcpStatBuilder.Append("=================================================\n");

            tcpStatBuilder.AppendFormat(" Minimum Transmission Timeout .. : {0}\n",
                tcpStat.MinimumTransmissionTimeout);
            tcpStatBuilder.AppendFormat(" Maximum Transmission Timeout .. : {0}\n",
                tcpStat.MaximumTransmissionTimeout);
            tcpStatBuilder.AppendFormat(" Maximum Connections ........... : {0}\n",
                tcpStat.MaximumConnections);

            tcpStatBuilder.AppendFormat(" Connection Data:\n");
            tcpStatBuilder.AppendFormat("  Current ...................... : {0}\n",
            tcpStat.CurrentConnections);
            tcpStatBuilder.AppendFormat("  Cumulative ................... : {0}\n",
                tcpStat.CumulativeConnections);
            tcpStatBuilder.AppendFormat("  Initiated .................... : {0}\n",
                tcpStat.ConnectionsInitiated);
            tcpStatBuilder.AppendFormat("  Accepted ..................... : {0}\n",
                tcpStat.ConnectionsAccepted);
            tcpStatBuilder.AppendFormat("  Failed Attempts .............. : {0}\n",
                tcpStat.FailedConnectionAttempts);
            tcpStatBuilder.AppendFormat("  Reset ........................ : {0}\n",
                tcpStat.ResetConnections);
            tcpStatBuilder.AppendFormat("  Errors ....................... : {0}\n",
                tcpStat.ErrorsReceived);

            tcpStatBuilder.AppendFormat(" Segment Data:\n");
            tcpStatBuilder.AppendFormat("  Received ..................... : {0}\n",
                tcpStat.SegmentsReceived);
            tcpStatBuilder.AppendFormat("  Sent ......................... : {0}\n",
                tcpStat.SegmentsSent);
            tcpStatBuilder.AppendFormat("  Retransmitted ................ : {0}\n",
                tcpStat.SegmentsResent);
            tcpStatBuilder.AppendFormat("  Resent with reset ............ : {0}\n",
                tcpStat.ResetsSent);

            TcpConnectionInformation[] connectionsInfo = properties.GetActiveTcpConnections();

            tcpStatBuilder.AppendFormat(" Active Connections ............ : {0}\n",
                connectionsInfo.Length);

            if (connectionsInfo.Length > 0)
            {
                tcpStatBuilder.Append("  Local Address   Port   Remote Address  Port\n");
            }

            foreach (TcpConnectionInformation connectionInfo in connectionsInfo)
            {
                tcpStatBuilder.AppendFormat("  {0, -15}:{1}   {2, -15}:{3}\n",
                    connectionInfo.LocalEndPoint.Address,
                    connectionInfo.LocalEndPoint.Port,
                    connectionInfo.RemoteEndPoint.Address,
                    connectionInfo.RemoteEndPoint.Port);
            }

            IPEndPoint[] endPoints = properties.GetActiveTcpListeners();

            tcpStatBuilder.AppendFormat(" TCP Listeners ................. : {0}\n",
                endPoints.Length);

            if (endPoints.Length > 0)
            {
                tcpStatBuilder.Append("  Local Address   Port\n");
            }

            foreach (IPEndPoint endPoint in endPoints)
            {
                tcpStatBuilder.AppendFormat("  {0, -15}:{1}\n",
                    endPoint.Address, endPoint.Port);
            }

            return tcpStatBuilder.ToString();
        }
Example #31
0
 static frmAdvanced()
 {
     ProtocolVersion         = NetworkInterfaceComponent.IPv4;
     nfi.NumberDecimalDigits = 0; //we don't want decimals !
 }
Example #32
0
 public override bool Supports(NetworkInterfaceComponent networkInterfaceComponent)
 {
     throw NotImplemented.ByDesign;
 }
        private string GetUdpStatistics(
            NetworkInterfaceComponent version,
            IPGlobalProperties properties)
        {
            UdpStatistics udpStat = null;

            StringBuilder udpStatBuilder = new StringBuilder();

            try
            {
                switch (version)
                {
                    case NetworkInterfaceComponent.IPv4:
                        udpStat = properties.GetUdpIPv4Statistics();
                        udpStatBuilder.Append("UDP IPv4 Statistics\n");
                        break;
                    case NetworkInterfaceComponent.IPv6:
                        udpStat = properties.GetUdpIPv6Statistics();
                        udpStatBuilder.Append("UDP IPv6 Statistics\n");
                        break;
                    default:
                        throw new ArgumentException("No such IP version");
                }
            }
            catch (NetworkInformationException)
            {
                return String.Empty;
            }

            udpStatBuilder.Append("=================================================\n");

            udpStatBuilder.AppendFormat(" Datagrams Received ............ : {0}\n",
                udpStat.DatagramsReceived);
            udpStatBuilder.AppendFormat(" Datagrams Sent ................ : {0}\n",
                udpStat.DatagramsSent);
            udpStatBuilder.AppendFormat(" Incoming Datagrams Discarded .. : {0}\n",
                udpStat.IncomingDatagramsDiscarded);
            udpStatBuilder.AppendFormat(" Incoming Datagrams With Errors  : {0}\n",
                udpStat.IncomingDatagramsWithErrors);
            udpStatBuilder.AppendFormat(" UDP Listeners ................. : {0}\n",
                udpStat.UdpListeners);

            IPEndPoint[] endPoints = properties.GetActiveUdpListeners();

            if (endPoints.Length > 0)
            {
                udpStatBuilder.Append("  Local Address   Port\n");
            }

            foreach (IPEndPoint endPoint in endPoints)
            {
                udpStatBuilder.AppendFormat("  {0, -15}:{1}\n",
                    endPoint.Address, endPoint.Port);
            }

            return udpStatBuilder.ToString();
        }
Example #34
0
		static bool IsProtocolSupported (NetworkInterfaceComponent networkInterface)
		{
#if MOBILE
			return true;
#else
			var nics = NetworkInterface.GetAllNetworkInterfaces ();
			foreach (var adapter in nics) {
				if (adapter.Supports (networkInterface))
					return true;
			}

			return false;
#endif
		}
	public abstract virtual bool Supports(NetworkInterfaceComponent networkInterfaceComponent) {}
Example #36
0
 /// <inheritdoc />
 public bool Supports(NetworkInterfaceComponent networkInterfaceComponent)
 {
     return(_nic.Supports(networkInterfaceComponent));
 }
Example #37
0
 public virtual bool Supports(NetworkInterfaceComponent networkInterfaceComponent)
 {
     throw NotImplemented.ByDesignWithMessage(SR.net_MethodNotImplementedException);
 }
Example #38
0
        private void UpdateNICStats(NetworkInterfaceComponent version)
        {
            NetworkInterface        nic = (NetworkInterface)comboInterfaces.SelectedItem;
            IPInterfaceProperties   ipip;   // ipv4 & ipv6
            IPv4InterfaceStatistics ipv4is; // ipv4 only
            IPv4InterfaceProperties ipv4ip; // ipv4 only
            IPv6InterfaceProperties ipv6ip; // ipv6 only


            try
            {
                ipip = nic.GetIPProperties(); // ipv4 & ipv6
            }
            catch
            {
                ipip = null;
            }

            try
            {
                ipv4is = nic.GetIPv4Statistics(); // ipv4 only
            }
            catch
            {
                ipv4is = null;
            }

            try
            {
                ipv4ip = ipip.GetIPv4Properties(); // ipv4 only
            }
            catch
            {
                ipv4ip = null;
            }

            try
            {
                ipv6ip = ipip.GetIPv6Properties(); // ipv6 only
            }
            catch
            {
                ipv6ip = null;
            }


            StringBuilder builder   = new StringBuilder();
            string        speedunit = String.Empty;

            byte[] mac;

            if (version == NetworkInterfaceComponent.IPv4 || ipv6ip == null)
            {
                if (ipv4is != null)
                {
                    txtBytesReceived.Text                  = ipv4is.BytesReceived.ToString("n", nfi);
                    txtIncomingPacketsDiscarded.Text       = ipv4is.IncomingPacketsDiscarded.ToString("n", nfi);
                    txtIncomingPacketsWithErrors.Text      = ipv4is.IncomingPacketsWithErrors.ToString("n", nfi);
                    txtIncomingUnknownProtocolPackets.Text = ipv4is.IncomingUnknownProtocolPackets.ToString("n", nfi);
                    txtNonUnicastPacketsReceived.Text      = ipv4is.NonUnicastPacketsReceived.ToString("n", nfi);
                    txtUnicastPacketsReceived.Text         = ipv4is.UnicastPacketsReceived.ToString("n", nfi);

                    txtBytesSent.Text                 = ipv4is.BytesSent.ToString("n", nfi);
                    txtNonUnicastPacketsSent.Text     = ipv4is.NonUnicastPacketsSent.ToString("n", nfi);
                    txtUnicastPacketsSent.Text        = ipv4is.UnicastPacketsSent.ToString("n", nfi);
                    txtOutgoingPacketsDiscarded.Text  = ipv4is.OutgoingPacketsDiscarded.ToString("n", nfi);
                    txtOutgoingPacketsWithErrors.Text = ipv4is.OutgoingPacketsWithErrors.ToString("n", nfi);
                    txtOutputQueueLength.Text         = ipv4is.OutputQueueLength.ToString("n", nfi);
                }
                else
                {
                    txtBytesReceived.Text                  = String.Empty;
                    txtIncomingPacketsDiscarded.Text       = String.Empty;
                    txtIncomingPacketsWithErrors.Text      = String.Empty;
                    txtIncomingUnknownProtocolPackets.Text = String.Empty;
                    txtNonUnicastPacketsReceived.Text      = String.Empty;
                    txtUnicastPacketsReceived.Text         = String.Empty;

                    txtBytesSent.Text                 = String.Empty;
                    txtNonUnicastPacketsSent.Text     = String.Empty;
                    txtUnicastPacketsSent.Text        = String.Empty;
                    txtOutgoingPacketsDiscarded.Text  = String.Empty;
                    txtOutgoingPacketsWithErrors.Text = String.Empty;
                    txtOutputQueueLength.Text         = String.Empty;
                }

                if (ipv4ip != null)
                {
                    txtIndex.Text = ipv4ip.Index.ToString("n", nfi);
                    txtIsAutomaticPrivateAddressingActive.Text  = ipv4ip.IsAutomaticPrivateAddressingActive ? Res.str_Yes : Res.str_No;
                    txtIsAutomaticPrivateAddressingEnabled.Text = ipv4ip.IsAutomaticPrivateAddressingEnabled ? Res.str_Yes : Res.str_No;
                    txtIsDhcpEnabled.Text       = ipv4ip.IsDhcpEnabled ? Res.str_Yes : Res.str_No;
                    txtIsForwardingEnabled.Text = ipv4ip.IsForwardingEnabled ? Res.str_Yes : Res.str_No;
                    txtMtu.Text      = ipv4ip.Mtu.ToString("n", nfi);
                    txtUsesWins.Text = ipv4ip.UsesWins ? Res.str_Yes : Res.str_No;
                }
                else
                {
                    txtIndex.Text = String.Empty;
                    txtIsAutomaticPrivateAddressingActive.Text  = String.Empty;
                    txtIsAutomaticPrivateAddressingEnabled.Text = String.Empty;
                    txtIsDhcpEnabled.Text       = String.Empty;
                    txtIsForwardingEnabled.Text = String.Empty;
                    txtMtu.Text      = String.Empty;
                    txtUsesWins.Text = String.Empty;
                }
            }
            else
            {
                txtBytesReceived.Text                  = String.Empty;
                txtIncomingPacketsDiscarded.Text       = String.Empty;
                txtIncomingPacketsWithErrors.Text      = String.Empty;
                txtIncomingUnknownProtocolPackets.Text = String.Empty;
                txtNonUnicastPacketsReceived.Text      = String.Empty;
                txtUnicastPacketsReceived.Text         = String.Empty;

                txtBytesSent.Text                 = String.Empty;
                txtNonUnicastPacketsSent.Text     = String.Empty;
                txtUnicastPacketsSent.Text        = String.Empty;
                txtOutgoingPacketsDiscarded.Text  = String.Empty;
                txtOutgoingPacketsWithErrors.Text = String.Empty;
                txtOutputQueueLength.Text         = String.Empty;

                txtIsAutomaticPrivateAddressingActive.Text  = String.Empty;
                txtIsAutomaticPrivateAddressingEnabled.Text = String.Empty;
                txtIsDhcpEnabled.Text       = String.Empty;
                txtIsForwardingEnabled.Text = String.Empty;
                txtUsesWins.Text            = String.Empty;

                if (ipv6ip != null)
                {
                    txtMtu.Text   = ipv6ip.Mtu.ToString("n", nfi);
                    txtIndex.Text = ipv6ip.Index.ToString("n", nfi);
                }
                else
                {
                    txtMtu.Text   = String.Empty;
                    txtIndex.Text = String.Empty;
                }
            }

            if (nic != null)
            {
                txtDescription.Text          = nic.Description;
                txtName.Text                 = nic.Name;
                txtSpeed.Text                = String.Format("{0} {1}/s", MainForm.computeSpeed(nic.Speed, ref speedunit, 2).ToString("n", nfi), speedunit);
                txtNetworkInterfaceType.Text = nic.NetworkInterfaceType.ToString();

                mac = nic.GetPhysicalAddress().GetAddressBytes();
                if (mac.Length == 6) // MAC-48
                {
                    txtMACaddress.Text = String.Format("{0:X2}-{1:X2}-{2:X2}-{3:X2}-{4:X2}-{5:X2}", mac[0], mac[1], mac[2], mac[3], mac[4], mac[5]);
                }
                else if (mac.Length == 8) // EUI-64 (MAC-48 + 0xFFFE)
                {
                    txtMACaddress.Text = String.Format("{0:X2}-{1:X2}-{2:X2}-{3:X2}-{4:X2}-{5:X2}-{6:X2}-{7:X2}", mac[0], mac[1], mac[2], mac[3], mac[4], mac[5], mac[6], mac[7]);
                }
                else if (mac.Length == 0) // Loopback interface for example
                {
                    txtMACaddress.Text = Res.str_None;
                }
                else // We got a winner here...
                {
                    txtMACaddress.Text = Res.str_Unsupported;
                }

                txtId.Text                     = nic.Id;
                txtIsReceiveOnly.Text          = nic.IsReceiveOnly ? Res.str_Yes : Res.str_No;
                txtOperationalStatus.Text      = nic.OperationalStatus.ToString();
                txtLoopbackInterfaceIndex.Text = NetworkInterface.LoopbackInterfaceIndex.ToString("n", nfi);
                txtSupportsMulticast.Text      = nic.SupportsMulticast ? Res.str_Yes : Res.str_No;
            }
            else
            {
                txtDescription.Text          = String.Empty;
                txtName.Text                 = String.Empty;
                txtSpeed.Text                = String.Empty;
                txtNetworkInterfaceType.Text = String.Empty;
                txtId.Text                     = String.Empty;
                txtIsReceiveOnly.Text          = String.Empty;
                txtOperationalStatus.Text      = String.Empty;
                txtLoopbackInterfaceIndex.Text = String.Empty;
                txtSupportsMulticast.Text      = String.Empty;
            }

            if (ipip != null)
            {
                builder.Remove(0, builder.Length);
                foreach (IPAddressInformation ip in ipip.AnycastAddresses)
                {
                    builder.Append(String.Format("{0} ; ", ip.Address.ToString()));
                }
                txtAnycastAddresses.Text = builder.ToString();

                builder.Remove(0, builder.Length);
                foreach (IPAddress ip in ipip.DhcpServerAddresses)
                {
                    builder.Append(String.Format("{0} ; ", ip.ToString()));
                }
                txtDhcpServerAddresses.Text = builder.ToString();

                builder.Remove(0, builder.Length);
                foreach (IPAddress ip in ipip.DnsAddresses)
                {
                    builder.Append(String.Format("{0} ; ", ip.ToString()));
                }
                txtDnsAddresses.Text = builder.ToString();

                txtDnsSuffix.Text = ipip.DnsSuffix;

                builder.Remove(0, builder.Length);
                foreach (GatewayIPAddressInformation ip in ipip.GatewayAddresses)
                {
                    builder.Append(String.Format("{0} ; ", ip.Address.ToString()));
                }
                txtGatewayAddresses.Text = builder.ToString();

                txtIsDnsEnabled.Text        = ipip.IsDnsEnabled ? Res.str_Yes : Res.str_No;
                txtIsDynamicDnsEnabled.Text = ipip.IsDynamicDnsEnabled ? Res.str_Yes : Res.str_No;

                builder.Remove(0, builder.Length);
                foreach (MulticastIPAddressInformation ip in ipip.MulticastAddresses)
                {
                    builder.Append(String.Format("{0} ; ", ip.Address.ToString()));
                }
                txtMulticastAddresses.Text = builder.ToString();

                builder.Remove(0, builder.Length);
                foreach (UnicastIPAddressInformation ip in ipip.UnicastAddresses)
                {
                    builder.Append(String.Format("{0} ; ", ip.Address.ToString()));
                }
                txtUnicastAddresses.Text = builder.ToString();

                builder.Remove(0, builder.Length);
                foreach (IPAddress ip in ipip.WinsServersAddresses)
                {
                    builder.Append(String.Format("{0} ; ", ip.ToString()));
                }
                txtWinsServersAddresses.Text = builder.ToString();
            }
            else
            {
                txtAnycastAddresses.Text     = String.Empty;
                txtDhcpServerAddresses.Text  = String.Empty;
                txtDnsAddresses.Text         = String.Empty;
                txtDnsSuffix.Text            = String.Empty;
                txtGatewayAddresses.Text     = String.Empty;
                txtIsDnsEnabled.Text         = String.Empty;
                txtIsDynamicDnsEnabled.Text  = String.Empty;
                txtMulticastAddresses.Text   = String.Empty;
                txtUnicastAddresses.Text     = String.Empty;
                txtWinsServersAddresses.Text = String.Empty;
            }
        }
        /// <summary>
        ///     Set's the IPv4 or IPv6 DNS Servers of an interface.
        /// </summary>
        /// <param name="localNetworkInterface">The interface to work with.</param>
        /// <param name="dnsServers">List of dns servers to set.</param>
        /// <param name="networkInterfaceComponent">IPv4 or IPv6.</param>
        /// <returns><c>true</c> on success, otherwise <c>false</c></returns>
        /// <remarks>Win32_NetworkAdapter class is deprecated.
        /// https://msdn.microsoft.com/en-us/library/windows/desktop/hh968170(v=vs.85).aspx (only on windows 8+)</remarks>
        public static bool SetNameservers(LocalNetworkInterface localNetworkInterface, List <string> dnsServers,
                                          NetworkInterfaceComponent networkInterfaceComponent = NetworkInterfaceComponent.IPv4)
        {
            var status = false;

            if (networkInterfaceComponent == NetworkInterfaceComponent.IPv4)
            {
                using (var networkConfigMng = new ManagementClass("Win32_NetworkAdapterConfiguration"))
                {
                    using (var networkConfigs = networkConfigMng.GetInstances())
                    {
                        //(bool)mo["IPEnabled"] &&
                        foreach (
                            var managementObject in
                            networkConfigs.Cast <ManagementObject>()
                            .Where(mo => (string)mo["Description"] == localNetworkInterface.Description))
                        {
                            var enabled = (bool)managementObject["IPEnabled"];
                            if (enabled)
                            {
                                // the network adapter is enabled, so we can change the dns settings per WMI.
                                using (var newDns = managementObject.GetMethodParameters("SetDNSServerSearchOrder"))
                                {
                                    newDns["DNSServerSearchOrder"] = dnsServers.ToArray();
                                    var outputBaseObject = managementObject.InvokeMethod("SetDNSServerSearchOrder", newDns, null);
                                    if (outputBaseObject == null)
                                    {
                                        continue;
                                    }
                                    var state = (uint)outputBaseObject["returnValue"];
                                    switch (state)
                                    {
                                    case 0:                                             // Successful completion, no reboot required
                                    case 1:                                             // Successful completion, reboot required
                                        status = true;
                                        break;

                                    case 84:                                             // IP not enabled on adapter
                                        status = false;
                                        break;

                                    default:
                                        status = false;
                                        break;
                                    }
                                }
                            }
                            else
                            {
                                // seems to be unplugged or disabled, so we need change this per registry (not optimal)
                                var registryId = managementObject["SettingID"];
                                if (registryId == null)
                                {
                                    continue;
                                }
                                var localMachine   = Registry.LocalMachine;
                                var interfaceEntry = localMachine.OpenSubKey(
                                    @"SYSTEM\\CurrentControlSet\\Services\\Tcpip\\Parameters\\Interfaces\\" + registryId, true);
                                if (interfaceEntry == null)
                                {
                                    continue;
                                }
                                interfaceEntry.SetValue("NameServer", dnsServers.Count > 0 ? string.Join(",", dnsServers.ToArray()) : "",
                                                        RegistryValueKind.String);
                                status = true;
                            }
                        }
                    }
                }
            }
            else
            {
                //TODO: find better way to set IPv6 nameservers
                using (var process = new Process())
                {
                    var processStartInfo = new ProcessStartInfo("netsh",
                                                                "interface ipv6 delete dns \"" + localNetworkInterface.Name + "\" all")
                    {
                        WindowStyle    = ProcessWindowStyle.Hidden,
                        CreateNoWindow = true
                    };
                    process.StartInfo = processStartInfo;
                    process.Start();

                    foreach (var address in dnsServers)
                    {
                        //netsh interface ipv6 add dns "Interface Name" 127.0.0.1 validate=no
                        processStartInfo = new ProcessStartInfo("netsh",
                                                                "interface ipv6 add dns \"" + localNetworkInterface.Name + "\" " + address + " validate=no")
                        {
                            WindowStyle    = ProcessWindowStyle.Hidden,
                            CreateNoWindow = true
                        };
                        process.StartInfo = processStartInfo;
                        process.Start();
                    }
                    status = true;
                }
            }
            return(status);
        }
        private string GetIPGlobalStatistics(
            NetworkInterfaceComponent version,
            IPGlobalProperties properties)
        {
            IPGlobalStatistics ipStat = null;

            StringBuilder ipStatBuilder = new StringBuilder();

            try
            {
                switch (version)
                {
                    case NetworkInterfaceComponent.IPv4:
                        ipStat = properties.GetIPv4GlobalStatistics();
                        ipStatBuilder.Append("IPv4 Global Statistics\n");
                        break;
                    case NetworkInterfaceComponent.IPv6:
                        ipStat = properties.GetIPv6GlobalStatistics();
                        ipStatBuilder.Append("IPv6 Global Statistics:");
                        break;
                    default:
                        throw new ArgumentException("No such IP version");

                }
            }
            catch (NetworkInformationException)
            {
                return String.Empty;
            }

            ipStatBuilder.Append("=================================================\n");

            ipStatBuilder.AppendFormat(" Computer name ................. : {0}\n",
                properties.HostName);
            ipStatBuilder.AppendFormat(" Domain name ................... : {0}\n",
                properties.DomainName);
            ipStatBuilder.AppendFormat(" Node type ..................... : {0}\n",
                properties.NodeType);
            ipStatBuilder.AppendFormat(" DHCP scope .................... : {0}\n",
                properties.DhcpScopeName);
            ipStatBuilder.AppendFormat(" Is WINS proxy ................. : {0}\n",
                properties.IsWinsProxy);

            ipStatBuilder.AppendFormat(" Forwarding enabled ............ : {0}\n",
                ipStat.ForwardingEnabled);
            ipStatBuilder.AppendFormat(" Interfaces .................... : {0}\n",
                ipStat.NumberOfInterfaces);
            ipStatBuilder.AppendFormat(" IP addresses .................. : {0}\n",
                ipStat.NumberOfIPAddresses);
            ipStatBuilder.AppendFormat(" Routes ........................ : {0}\n",
                ipStat.NumberOfRoutes);
            ipStatBuilder.AppendFormat(" Default TTL ................... : {0}\n\n",
                ipStat.DefaultTtl);

            ipStatBuilder.AppendFormat(" Inbound Packet Data:\n");
            ipStatBuilder.AppendFormat("  Received ..................... : {0}\n",
                ipStat.ReceivedPackets);
            ipStatBuilder.AppendFormat("  Forwarded .................... : {0}\n",
                ipStat.ReceivedPacketsForwarded);
            ipStatBuilder.AppendFormat("  Delivered .................... : {0}\n",
                ipStat.ReceivedPacketsDelivered);
            ipStatBuilder.AppendFormat("  Discarded .................... : {0}\n",
                ipStat.ReceivedPacketsDiscarded);
            ipStatBuilder.AppendFormat("  Header Errors ................ : {0}\n",
                ipStat.ReceivedPacketsWithHeadersErrors);
            ipStatBuilder.AppendFormat("  Address Errors ............... : {0}\n",
                ipStat.ReceivedPacketsWithAddressErrors);
            ipStatBuilder.AppendFormat("  Unknown Protocol Errors ...... : {0}\n\n",
                ipStat.ReceivedPacketsWithUnknownProtocol);

            ipStatBuilder.AppendFormat(" Outbound Packet Data:\n");
            ipStatBuilder.AppendFormat("  Requested .................... : {0}\n",
                 ipStat.OutputPacketRequests);
            ipStatBuilder.AppendFormat("  Discarded .................... : {0}\n",
                ipStat.OutputPacketsDiscarded);
            ipStatBuilder.AppendFormat("  No Routing Discards .......... : {0}\n",
                ipStat.OutputPacketsWithNoRoute);
            ipStatBuilder.AppendFormat("  Routing Entry Discards ....... : {0}\n\n",
                ipStat.OutputPacketRoutingDiscards);

            ipStatBuilder.AppendFormat(" Reassembly Data:\n");
            ipStatBuilder.AppendFormat("  Reassembly Timeout ........... : {0}\n",
                ipStat.PacketReassemblyTimeout);
            ipStatBuilder.AppendFormat("  Reassemblies Required ........ : {0}\n",
                ipStat.PacketReassembliesRequired);
            ipStatBuilder.AppendFormat("  Reassembly Failures .......... : {0}\n",
                ipStat.PacketReassemblyFailures);
            ipStatBuilder.AppendFormat("  Packets Reassembled .......... : {0}\n",
                ipStat.PacketsReassembled);
            ipStatBuilder.AppendFormat("  Packets Fragmented ........... : {0}\n",
                ipStat.PacketsFragmented);
            ipStatBuilder.AppendFormat("  Fragment Failures ............ : {0}\n",
                ipStat.PacketFragmentFailures);

            return ipStatBuilder.ToString();
        }
Example #41
0
 public abstract bool Supports(NetworkInterfaceComponent networkInterfaceComponent);
Example #42
0
 public static void ShowIPStatistics(NetworkInterfaceComponent version)
 {
     IPGlobalProperties properties = IPGlobalProperties.GetIPGlobalProperties();
     IPGlobalStatistics ipstat = null;
     switch (version)
     {
     case NetworkInterfaceComponent.IPv4:
         ipstat = properties.GetIPv4GlobalStatistics();
         Console.WriteLine("{0}IPv4 Statistics ",Environment.NewLine);
         break;
     case NetworkInterfaceComponent.IPv6:
         ipstat = properties.GetIPv4GlobalStatistics();
         Console.WriteLine("{0}IPv6 Statistics ",Environment.NewLine);
         break;
     default:
         throw new ArgumentException("version");
         //    break;
     }
     Console.WriteLine("  Forwarding enabled ...................... : {0}",
     ipstat.ForwardingEnabled);
     Console.WriteLine("  Interfaces .............................. : {0}",
     ipstat.NumberOfInterfaces);
     Console.WriteLine("  IP addresses ............................ : {0}",
     ipstat.NumberOfIPAddresses);
     Console.WriteLine("  Routes .................................. : {0}",
     ipstat.NumberOfRoutes);
     Console.WriteLine("  Default TTL ............................. : {0}",
     ipstat.DefaultTtl);
     Console.WriteLine("");
     Console.WriteLine("  Inbound Packet Data:");
     Console.WriteLine("      Received ............................ : {0}",
     ipstat.ReceivedPackets);
     Console.WriteLine("      Forwarded ........................... : {0}",
     ipstat.ReceivedPacketsForwarded);
     Console.WriteLine("      Delivered ........................... : {0}",
     ipstat.ReceivedPacketsDelivered);
     Console.WriteLine("      Discarded ........................... : {0}",
     ipstat.ReceivedPacketsDiscarded);
     Console.WriteLine("      Header Errors ....................... : {0}",
     ipstat.ReceivedPacketsWithHeadersErrors);
     Console.WriteLine("      Address Errors ...................... : {0}",
     ipstat.ReceivedPacketsWithAddressErrors);
     Console.WriteLine("      Unknown Protocol Errors ............. : {0}",
     ipstat.ReceivedPacketsWithUnknownProtocol);
     Console.WriteLine("");
     Console.WriteLine("  Outbound Packet Data:");
     Console.WriteLine("      Requested ........................... : {0}",
     ipstat.OutputPacketRequests);
     Console.WriteLine("      Discarded ........................... : {0}",
     ipstat.OutputPacketsDiscarded);
     Console.WriteLine("      No Routing Discards ................. : {0}",
     ipstat.OutputPacketsWithNoRoute);
     Console.WriteLine("      Routing Entry Discards .............. : {0}",
     ipstat.OutputPacketRoutingDiscards);
     Console.WriteLine("");
     Console.WriteLine("  Reassembly Data:");
     Console.WriteLine("      Reassembly Timeout .................. : {0}",
     ipstat.PacketReassemblyTimeout);
     Console.WriteLine("      Reassemblies Required ............... : {0}",
     ipstat.PacketReassembliesRequired);
     Console.WriteLine("      Packets Reassembled ................. : {0}",
     ipstat.PacketsReassembled);
     Console.WriteLine("      Packets Fragmented .................. : {0}",
     ipstat.PacketsFragmented);
     Console.WriteLine("      Fragment Failures ................... : {0}",
     ipstat.PacketFragmentFailures);
     Console.WriteLine("");
 }
Example #43
0
		public abstract bool Supports (NetworkInterfaceComponent networkInterfaceComponent);
        /// <summary>
        ///     Set's the IPv4 or IPv6 DNS Servers of an interface.
        /// </summary>
        /// <param name="localNetworkInterface">The interface to work with.</param>
        /// <param name="dnsServers">List of dns servers to set.</param>
        /// <param name="networkInterfaceComponent">IPv4 or IPv6.</param>
        /// <returns><c>true</c> on success, otherwise <c>false</c></returns>
        /// <remarks>Win32_NetworkAdapter class is deprecated.
        /// https://msdn.microsoft.com/en-us/library/windows/desktop/hh968170(v=vs.85).aspx (only on windows 8+)</remarks>
        public static bool SetNameservers(LocalNetworkInterface localNetworkInterface, List<string> dnsServers,
			NetworkInterfaceComponent networkInterfaceComponent = NetworkInterfaceComponent.IPv4)
        {
            var status = false;
            if (networkInterfaceComponent == NetworkInterfaceComponent.IPv4)
            {
                using (var networkConfigMng = new ManagementClass("Win32_NetworkAdapterConfiguration"))
                {
                    using (var networkConfigs = networkConfigMng.GetInstances())
                    {
                        //(bool)mo["IPEnabled"] &&
                        foreach (
                            var managementObject in
                                networkConfigs.Cast<ManagementObject>()
                                    .Where(mo => (string)mo["Description"] == localNetworkInterface.Description))
                        {
                            var enabled = (bool)managementObject["IPEnabled"];
                            if (enabled)
                            {
                                // the network adapter is enabled, so we can change the dns settings per WMI.
                                using (var newDns = managementObject.GetMethodParameters("SetDNSServerSearchOrder"))
                                {
                                    newDns["DNSServerSearchOrder"] = dnsServers.ToArray();
                                    var outputBaseObject = managementObject.InvokeMethod("SetDNSServerSearchOrder", newDns, null);
                                    if (outputBaseObject == null) continue;
                                    var state = (uint)outputBaseObject["returnValue"];
                                    switch (state)
                                    {
                                        case 0: // Successful completion, no reboot required
                                        case 1: // Successful completion, reboot required
                                            status = true;
                                            break;
                                        case 84: // IP not enabled on adapter
                                            status = false;
                                            break;
                                        default:
                                            status = false;
                                            break;
                                    }
                                }
                            }
                            else
                            {
                                // seems to be unplugged or disabled, so we need change this per registry (not optimal)
                                var registryId = managementObject["SettingID"];
                                if (registryId == null) continue;
                                var localMachine = Registry.LocalMachine;
                                var interfaceEntry = localMachine.OpenSubKey(
                                    @"SYSTEM\\CurrentControlSet\\Services\\Tcpip\\Parameters\\Interfaces\\" + registryId, true);
                                if (interfaceEntry == null) continue;
                                interfaceEntry.SetValue("NameServer", dnsServers.Count > 0 ? string.Join(",", dnsServers.ToArray()) : "",
                                    RegistryValueKind.String);
                                status = true;
                            }
                        }
                    }
                }
            }
            else
            {
                //TODO: find better way to set IPv6 nameservers
                using (var process = new Process())
                {
                    var processStartInfo = new ProcessStartInfo("netsh",
                        "interface ipv6 delete dns \"" + localNetworkInterface.Name + "\" all")
                    {
                        WindowStyle = ProcessWindowStyle.Hidden,
                        CreateNoWindow = true
                    };
                    process.StartInfo = processStartInfo;
                    process.Start();

                    foreach (var address in dnsServers)
                    {
                        //netsh interface ipv6 add dns "Interface Name" 127.0.0.1 validate=no
                        processStartInfo = new ProcessStartInfo("netsh",
                            "interface ipv6 add dns \"" + localNetworkInterface.Name + "\" " + address + " validate=no")
                        {
                            WindowStyle = ProcessWindowStyle.Hidden,
                            CreateNoWindow = true
                        };
                        process.StartInfo = processStartInfo;
                        process.Start();
                    }
                    status = true;
                }
            }
            return status;
        }
Example #45
0
		public override bool Supports (NetworkInterfaceComponent networkInterfaceComponent)
		{
			switch (networkInterfaceComponent) {
			case NetworkInterfaceComponent.IPv4:
				return mib4.Index >= 0;
			case NetworkInterfaceComponent.IPv6:
				return mib6.Index >= 0;
			}
			return false;
		}
 public override bool Supports(NetworkInterfaceComponent networkInterfaceComponent)
 {
     return(true);
 }
        /// <summary>
        ///     Get the nameservers of an interface.
        /// </summary>
        /// <param name="localNetworkInterface">The interface to extract from.</param>
        /// <param name="networkInterfaceComponent">IPv4 or IPv6.</param>
        /// <returns>A list of nameservers.</returns>
        internal static List<string> GetDnsServerList(string localNetworkInterface,
			NetworkInterfaceComponent networkInterfaceComponent)
        {
            var serverAddresses = new List<string>();
            try
            {
                var registryKey = networkInterfaceComponent == NetworkInterfaceComponent.IPv6
                    ? Registry.GetValue(
                        "HKEY_LOCAL_MACHINE\\SYSTEM\\CurrentControlSet\\Services\\TCPIP6\\Parameters\\Interfaces\\" +
                        localNetworkInterface,
                        "NameServer", "")
                    : Registry.GetValue(
                        "HKEY_LOCAL_MACHINE\\SYSTEM\\CurrentControlSet\\Services\\Tcpip\\Parameters\\Interfaces\\" +
                        localNetworkInterface,
                        "NameServer", "");

                if (registryKey != null && registryKey.ToString().Length > 0)
                {
                    serverAddresses =
                        new List<string>(((string) registryKey).Split(new[] {","}, StringSplitOptions.None));
                }
            }
            catch (Exception)
            {
            }
            return serverAddresses;
        }
Example #48
0
 public override bool Supports(NetworkInterfaceComponent networkInterfaceComponent)
 {
     return true;
 }
Example #49
0
 public override bool Supports(NetworkInterfaceComponent networkInterfaceComponent)
 {
     throw new NotImplementedException();
 }
 public override bool Supports(NetworkInterfaceComponent networkInterfaceComponent)
 {
     return(((networkInterfaceComponent == NetworkInterfaceComponent.IPv6) && (this.ipv6Index > 0)) || ((networkInterfaceComponent == NetworkInterfaceComponent.IPv4) && (this.index > 0)));
 }