Пример #1
0
        /// <summary>
        /// Set the network mask via M553
        /// </summary>
        /// <param name="index">Index of the network interface</param>
        /// <param name="netmask">Subnet mask</param>
        /// <returns>Configuration result</returns>
        public static async Task <string> ManageGateway(int index, IPAddress gateway, IPAddress dnsServer)
        {
            NetworkInterface iface = Get(index);

            if (gateway != null || dnsServer != null)
            {
                return(await DHCP.SetIPAddress(iface.Name, null, null, gateway, dnsServer));
            }

            if (iface.OperationalStatus == OperationalStatus.Up)
            {
                gateway = (from item in iface.GetIPProperties().GatewayAddresses
                           where item.Address.AddressFamily == AddressFamily.InterNetwork
                           select item.Address).FirstOrDefault() ?? IPAddress.Any;
                dnsServer = (from item in iface.GetIPProperties().DnsAddresses
                             where item.AddressFamily == AddressFamily.InterNetwork
                             select item).FirstOrDefault() ?? IPAddress.Any;
            }
            else
            {
                gateway = await DHCP.GetConfiguredGateway(iface.Name);

                dnsServer = await DHCP.GetConfiguredDNSServer(iface.Name);
            }

            StringBuilder builder = new();

            builder.AppendLine($"Gateway: {gateway}");
            builder.Append($"DNS server: {dnsServer}");
            return(builder.ToString());
        }
Пример #2
0
		private Nic(NetworkInterface ni)
		{
			_isInitializing = true;
			Reload(ni);
			_isInitializing = false;
			ConnectivityCheckRequired(this);
		}
Пример #3
0
        /// <summary>
        /// Checks local IP.
        /// </summary>
        /// <param name="ipAddr">IP Address</param>
        /// <returns>True if specified IP is equals to local one.</returns>
        private static bool CheckIpAddress(string ipAddr)
        {
            System.Net.NetworkInformation.NetworkInterface[] netInterfaces = null;
            try
            {
                netInterfaces = System.Net.NetworkInformation.NetworkInterface.GetAllNetworkInterfaces();
            }
            catch (NetworkInformationException ex)
            {
                //Logger.Log(ex.Message, EventLogEntryType.ERROR);
            }
            if (netInterfaces != null && !string.IsNullOrEmpty(ipAddr))
            {
                for (int i = 0; i < netInterfaces.Length; i++)
                {
                    System.Net.NetworkInformation.NetworkInterface netInterface = netInterfaces[i];
                    if (!netInterface.Supports(NetworkInterfaceComponent.IPv4))
                    {
                        continue;
                    }
                    foreach (UnicastIPAddressInformation addr in netInterface.GetIPProperties().UnicastAddresses)
                    {
                        if (ipAddr == addr.Address.ToString())
                        {
                            return(true);
                        }
                    }
                }
            }

            return(false);
        }
Пример #4
0
        private void CheckNetworkInterfaceStatuses(object sender, EventArgs e)
        {
            lock (_interfaceHandlers)
            {
                NetworkInterfaceInformation[] interfaceInfos = NetworkInterfaceInformation.GetAllNetworkInterfaces();
                foreach (NetworkInterfaceInformation interfaceInfo in interfaceInfos)
                {
                    if (interfaceInfo.NetworkInterfaceType == NetworkInterfaceType.Loopback)
                    {
                        continue;
                    }
                    if (interfaceInfo.NetworkInterfaceType == NetworkInterfaceType.Tunnel)
                    {
                        continue;
                    }

                    int index = interfaceInfo.GetIPProperties().GetIPv4Properties().Index;
                    NetworkInterfaceHandler interfaceHandler;
                    _interfaceHandlers.TryGetValue(index, out interfaceHandler);
                    if (interfaceHandler != null)
                    {
                        if (interfaceInfo.OperationalStatus == OperationalStatus.Up)
                        {
                            interfaceHandler.Enable();
                        }
                        else
                        {
                            interfaceHandler.Disable();
                        }
                    }
                }
            }
        }
Пример #5
0
        public static UpdateType GetUpdateType(NetworkInterface oldInterface, NetworkInterface newInterface)
        {
            if (oldInterface.Id != newInterface.Id)
                return UpdateType.Name;

            IPInterfaceProperties oldIPProps = oldInterface.GetIPProperties();
            IPInterfaceProperties newIPProps = newInterface.GetIPProperties();

            if (HasIPChanged(oldIPProps, newIPProps))
                return UpdateType.IP;

            if (HasNetmaskChanged(oldIPProps, newIPProps))
                return UpdateType.Netmask;

            if (HasGatewayChanged(oldIPProps, newIPProps))
                return UpdateType.Gateway;

            if (HasDHCPChanged(oldIPProps, newIPProps))
                return UpdateType.DHCP;

            if (HasDNSChanged(oldIPProps, newIPProps))
                return UpdateType.DNS;

            if (!oldIPProps.Equals(newIPProps))
                return UpdateType.Other;

            return UpdateType.None;
        }
Пример #6
0
 public NetInterface(int id, string name, NetInterfaceType type, NetworkInterface netIface)
 {
     NetshId = id;
     Name = name;
     Type = type;
     networkInterface = netIface;
 }
Пример #7
0
 public Client (NetworkInterface networkInterface)
 {
     network_interface_info = NetworkInterfaceInfo.GetNetworkInterfaceInfo (networkInterface);
     service_cache = new ServiceCache (this);
     notify_listener = new NotifyListener (this);
     browsers = new Dictionary<string, Browser> ();
 }
 /// <summary>
 /// Creates a new unicast network address information instance.
 /// </summary>
 /// <param name="iface">The network interface.</param>
 /// <param name="information">The address information.</param>
 public UnicastNetworkAddressInformation(NetworkInterface iface, UnicastIPAddressInformation information)
     : base(iface)
 {
     this.UnicastInformation = information;
     this.Stale = false;
     this.Selected = true;
 }
Пример #9
0
 public static NetworkInterfaceInfo GetNetworkInterfaceInfo (NetworkInterface networkInterface)
 {
     if (networkInterface == null) {
         return new NetworkInterfaceInfo (IPAddress.Any, 0);
     }
     var properties = networkInterface.GetIPProperties ();
     var ipv4_properties = properties.GetIPv4Properties ();
     if (ipv4_properties == null) {
         throw new ArgumentException ("The specified network interface does not support IPv4.", "networkInterface");
     }
     var host_name = Dns.GetHostName ();
     foreach (var address in properties.UnicastAddresses)
     {
         string addressHostname = null;
         try
         {
             addressHostname = Dns.GetHostEntry(address.Address).HostName;
         }
         catch(SocketException)
         {
             
         }
         if (address.Address.AddressFamily == AddressFamily.InterNetwork && addressHostname == host_name) {
             return new NetworkInterfaceInfo (address.Address, ipv4_properties.Index);
         }
     }
     throw new ArgumentException (string.Format (
         "The specified network interface does not have a suitable address for the local hostname: {0}.", host_name), "networkInterface");
 }
Пример #10
0
 public ChatServer(int portNumber, object networkInterface, string serverName)
 {
     this.serverName = serverName;
     this.portNumber = portNumber;
     this.networkInterface = networkInterface as NetworkInterface;
     CreateEventLog();
 }
Пример #11
0
        /// <summary>
        /// Assign a custom MAC address to a network adapter
        /// </summary>
        /// <param name="index">Index of the network interface</param>
        /// <param name="macAddress">MAC address to set</param>
        /// <returns>Command result</returns>
        public static async Task <Message> SetMACAddress(int index, string macAddress)
        {
            if (!PhysicalAddress.TryParse(macAddress.Replace(':', '-'), out PhysicalAddress parsedAddress))
            {
                throw new ArgumentException("Invalid MAC address");
            }

            StringBuilder    result = new();
            NetworkInterface iface  = Get(index);
            bool             isUp   = iface.OperationalStatus == OperationalStatus.Up;

            // Set link down (if needed)
            if (isUp)
            {
                string setDownResult = await Command.Execute("/usr/sbin/ip", $"link set dev {iface.Name} down");

                result.AppendLine(setDownResult);
            }

            // Update MAC address
            string setResult = await Command.Execute("/usr/sbin/ip", $"link set dev {iface.Name} address {BitConverter.ToString(parsedAddress.GetAddressBytes()).Replace('-', ':')}");

            result.AppendLine(setResult);

            // Set link up again (if needed)
            if (isUp)
            {
                string setUpResult = await Command.Execute("/usr/sbin/ip", $"link set dev {iface.Name} up");

                result.AppendLine(setUpResult);
            }

            return(new Message(MessageType.Success, result.ToString().Trim()));
        }
Пример #12
0
 public Server (string defaultLocation, NetworkInterface networkInterface)
 {
     default_location = defaultLocation;
     network_interface_info = NetworkInterfaceInfo.GetNetworkInterfaceInfo (networkInterface);
     request_listener = new RequestListener (this);
     announcers = new Dictionary<string, Announcer> ();
 }
Пример #13
0
 private void cmbInterface_SelectionChangeCommitted(object sender, EventArgs e)
 {
     timer.Enabled = false;
     Run = -1;
     nic = nicArr[cmbInterface.SelectedIndex];
     timer.Enabled = true;
 }
Пример #14
0
        public long getSentPackets( NetworkInterface conn )
        {
            IPInterfaceProperties properties = conn.GetIPProperties();
              IPv4InterfaceStatistics ipstat = conn.GetIPv4Statistics();

             return ipstat.BytesSent;
        }
Пример #15
0
        /*
           * Get received traffic
           * returns String[] array
          */
        public long getReceivedTraffic( NetworkInterface conn )
        {
            IPInterfaceProperties properties = conn.GetIPProperties();
             IPv4InterfaceStatistics ipstat = conn.GetIPv4Statistics();

             return ipstat.BytesReceived;
        }
Пример #16
0
 public SamsungTV(IPAddress tVIP4, string tVProductModel)
 {
     MyIP = MyComputer.GetComputerIPs(MyComputer.IPAddressSelectType.IPv4)[0];
     MyMAC = MyComputer.GetMacAddresses()[0];
     TVIP = tVIP4;
     TVProduct = tVProductModel;
     TVName = AppName + "." + TVProduct;
 }
Пример #17
0
 public NetworkDetector()
 {
     Logger.V(">> NetworkDetector.NetworkDetector");
     m_activeNetwork = null;
     m_activeIP = null;
     DetectActiveNetwork();
     Logger.V("<< NetworkDetector.NetworkDetector");
 }
Пример #18
0
        public NetworkCard(String name,String id,IPAddress ip)
        {
            _name = name;
            _id = id;
            _address = ip;
			_ni = GetInterfaceFromId(_id);
            
        }
Пример #19
0
        private static void RunAsConsoleApp()
        {
            if (!ServersWatcher.CredentialsCorrect)
            {
                // In case of empty credentials - show error message and exit
                Console.WriteLine("Error connecting to EC cloud - invalid connect data");
            }
            else
            {
                // Get list of running instances
                List <RunningInstance> instances = ServersWatcher.Instances;

                // Put it to console
                foreach (RunningInstance inst in instances)
                {
                    Console.WriteLine("{0} {1}", ServersWatcher.GetInstanceName(inst), inst.PrivateIpAddress);
                }
            }

            #if (DEBUG)
            System.Net.NetworkInformation.NetworkInterface[] netInterfaces = null;
            try
            {
                netInterfaces = System.Net.NetworkInformation.NetworkInterface.GetAllNetworkInterfaces();
            }
            catch //(NetworkInformationException ex)
            {
            }
            if (netInterfaces != null)
            {
                for (int i = 0; i < netInterfaces.Length; i++)
                {
                    System.Net.NetworkInformation.NetworkInterface netInterface = netInterfaces[i];
                    if (!netInterface.Supports(NetworkInterfaceComponent.IPv4))
                    {
                        continue;
                    }
                    foreach (UnicastIPAddressInformation addr in netInterface.GetIPProperties().UnicastAddresses)
                    {
                        Console.WriteLine(addr.Address);
                    }
                }
            }

            Console.WriteLine("\nService test starts.");
            Console.WriteLine("Start...");
            ConsoleStartTest();
            Console.WriteLine("Press any key...");
            Console.ReadKey();

            Console.WriteLine("Resume...");
            ConsoleInstanceTest();
            Console.WriteLine("Service test ended.\n");
#endif

            Console.WriteLine("press any key to exit");
            Console.ReadKey();
        }
Пример #20
0
 public static IPAddress GetGatewayAddressFromNetInterface(NetworkInterface intf)
 {
     IPInterfaceProperties ipProps = intf.GetIPProperties();
     if (ipProps == null)
         return IPAddress.Any;
     if (ipProps.GatewayAddresses == null || ipProps.GatewayAddresses.Count == 0)
         return IPAddress.Any;
     return ipProps.GatewayAddresses[0].Address;
 }
 public UploadSpeedEvent(NetworkInterface inter, int sent, int seconds, int comp)
 {
     _Interface = inter;
     _Sent = sent;
     _ToBeFor = seconds;
     _Comparator = comp;
     _LastValue = inter.GetIPv4Statistics().BytesSent;
     _Name = "Upload Speed Usage Event";
 }
Пример #22
0
        public NetworkAdapter(NetworkInterface networkInterface)
        {
            _networkInterface = networkInterface;

            Thread timer = new Thread(UpdateNetworkInterface);

            timer.IsBackground = true;
            timer.Start();
        }
 public DownloadSpeedEvent(NetworkInterface inter, int received, int seconds, int comp)
 {
     _Interface = inter;
     _Received = received;
     _ToBeFor = seconds;
     _Comparator = comp;
     _LastValue = inter.GetIPv4Statistics().BytesReceived;
     _Name = "Download Speed Usage Event";
 }
        private void UpdateNetworkInterface()
        {
            System.Net.NetworkInformation.NetworkInterface nic = nicArr[0];
            IPv4InterfaceStatistics interfaceStats             = nic.GetIPv4Statistics();
            int bytesReceivedSpeed = (int)(interfaceStats.BytesReceived - lblBytesReceived);

            lblBytesReceived = interfaceStats.BytesReceived;
            MainForm.updateDownloadSpeed(bytesReceivedSpeed);
            MainForm.updateEstimatedTime();
        }
Пример #25
0
 byte[] GetHardwareAddress(MNetworkInterface inf)
 {
     byte[] bytes = inf.GetPhysicalAddress().GetAddressBytes();
     // Map to android's idea of device address
     if (bytes.Length == 0 || inf.NetworkInterfaceType == NetworkInterfaceType.Tunnel)
     {
         return(null);
     }
     return(bytes);
 }
Пример #26
0
 public NetworkConfigModel(NetworkInterface ni)
 {
     var ip = ni.GetIPProperties();
     this.IpAddress = ip.UnicastAddresses.Count > 0 ? ip.UnicastAddresses[0].Address.ToString() : "";
     this.Gateway = ip.GatewayAddresses.Count > 0 ? ip.GatewayAddresses[0].Address.ToString() : "";
     this.Subnet = ip.UnicastAddresses.Count > 0 ? ip.UnicastAddresses[0].IPv4Mask.ToString() : "";
     this.DNSList = ip.DnsAddresses.Count > 0 ? string.Join(";", ip.DnsAddresses.Select(dn => dn.ToString())) : "";
     this.NetworkName = ni.Name;
     this.InterfaceName = ni.Description;
     this.UseDHCP = string.IsNullOrEmpty(this.IpAddress) && string.IsNullOrEmpty(this.Gateway);
 }
Пример #27
0
        public Boolean isNetworkConnected(NetworkInterface net)
        {
            Boolean bReturn = false;
            if (net != null && net.OperationalStatus == OperationalStatus.Up && net.GetIPProperties() != null && net.Description != null && net.NetworkInterfaceType != NetworkInterfaceType.Loopback) {
                bReturn =  true;
            }

            Helper.doLog("isNetworkConnected " + net.Id + " = " + bReturn, Properties.Settings.Default.DebugMode);

            return bReturn;
        }
Пример #28
0
		private void SetSocketOptionsForNic(NetworkInterface nic)
		{
			nic.GetIPProperties()
				.UnicastAddresses
				.Where(unicast => unicast.Address.AddressFamily == AddressFamily.InterNetwork)
				.ToList()
				.ForEach(
					address =>
					socket.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.AddMembership,
					                       new MulticastOption(IPAddress.Parse(AllHostsMulticastIP), address.Address)));
		}
        /// <summary>
        /// Shows the form as a dialog and the specified network interface.
        /// </summary>
        /// <param name="owner">The owner window.</param>
        /// <param name="iface">The network interface.</param>
        /// <returns>The dialog result.</returns>
        public DialogResult ShowDialog(IWin32Window owner, NetworkInterface iface)
        {
            // If the comment is null, do nothing.
            if (null == iface) return DialogResult.Abort;

            // Set the comment.
            this.control.Interface = iface;

            // Open the dialog.
            return base.ShowDialog(owner);
        }
Пример #30
0
        List <IPAddress> CollectAddresses(MNetworkInterface inf)
        {
            var ret = new List <IPAddress> ();

            foreach (UnicastIPAddressInformation addr in inf.GetIPProperties().UnicastAddresses)
            {
                ret.Add(addr.Address);
            }

            return(ret);
        }
Пример #31
0
        /// <summary>
        /// Returns the destination IP we'll later want to delete
        /// </summary>
        /// <param name="adapter"></param>
        /// <param name="hostOrIp"></param>
        /// <returns></returns>
        public static string AddRoute(NetworkInterface adapter, string hostOrIp )
        {
            IPAddress remoteAddress = null;
            if (IPAddress.TryParse(hostOrIp, out remoteAddress)) {
                // already an IP address
            } else {
                // resolve it
                try
                {
                    IPAddress[] addresslist = Dns.GetHostAddresses(hostOrIp);
                    if (addresslist.Length == 0)
                    {
                        MessageBox.Show("Can't resolve " + hostOrIp);
                    }
                    else
                    {
                        remoteAddress = addresslist[0];
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message, "Error");
                    return null;
                }

            }

            IPInterfaceProperties properties = adapter.GetIPProperties();

            try
            {
                if (remoteAddress != null)
                {
                    GatewayIPAddressInformationCollection gateways = properties.GatewayAddresses;
                        for (int j = 0; j < gateways.Count; j++)
                        {
                            GatewayIPAddressInformation gateway = gateways[j];

                            // Add the route entry to the route table to solve the Windows XP issue.
                            AddRoute(gateway.Address.ToString(), remoteAddress.ToString());
                        }
                }
            }

            catch (Exception ex)
            {
                //DebugEx.WriteException(ex);
                MessageBox.Show(ex.Message, "Error");
                return null;
            }

            return remoteAddress.ToString();
        }
Пример #32
0
        public static BooleanReason AddWirelessProfile(NetworkInterface adapter, string profile)
        {
            var handle = IntPtr.Zero;
            try
            {
                if (string.IsNullOrWhiteSpace(profile))
                {
                    Log.Warn("Cannot add wireless profile: profile text is empty");
                    return new BooleanReason(false, "Cannot add wireless profile: profile text is empty");
                }

                UInt32 negotiatedVersion;
                UInt32 version = 2;
                if (SystemUtilities.IsWindowsXp())
                    version = 1;

                var result = NativeWifi.WlanOpenHandle(version, IntPtr.Zero, out negotiatedVersion, out handle);
                if (result != 0)
                {
                    Log.WarnFormat("Could not open handle to native wifi interface: {0}", result);
                    return new BooleanReason(false, "Could not open handle to native wifi interface: {0}", result);
                }

                var identifier = new Guid(adapter.Id);
                NativeWifi.WlanReasonCode issueCode;

                result = NativeWifi.WlanSetProfile(
                    handle, identifier, NativeWifi.WlanProfileFlags.AllUser,
                    profile, null, true, IntPtr.Zero, out issueCode);

                if ((result != 0) && (result != 183))
                {
                    var issueText = GetTextForIssue(
                        "An issue occurred while attempting to set a wireless profile: {0}", issueCode);

                    Log.Warn(issueText);
                    return new BooleanReason(false, issueText);
                }

                return new BooleanReason(true, "");
            }

            catch (Exception e)
            {
                Log.Warn(e);
                return new BooleanReason(false, "An exception occurred while setting the wireless profile: {0}", e);
            }
            finally
            {
                if (handle != IntPtr.Zero)
                    NativeWifi.WlanCloseHandle(handle, IntPtr.Zero);
            }
        }
Пример #33
0
 public WifiWidget()
 {
     NetworkInterface[] interfaces = NetworkInterface.GetAllNetworkInterfaces();
     foreach (NetworkInterface inter in interfaces)
     {
         if (inter.NetworkInterfaceType == NetworkInterfaceType.Wireless80211)
         {
             _wifi = inter;
             break;
         }
     }
 }
Пример #34
0
        public static void getInterfacesInfo(ref NetworkInterface[] Net, ref string[,] Info)
        {
            Net = NetworkInterface.GetAllNetworkInterfaces();
            Info = new string[Net.Length, 3];

            for (int i = 0; i < Net.Length; i++)
            {
                Info[i, 0] = Net[i].Name.ToString();
                Info[i, 1] = Net[i].GetPhysicalAddress().ToString();
                Info[i, 2] = Net[i].OperationalStatus.ToString();
            }
        }
Пример #35
0
        public GoldDigger(NetworkInterface networkInterface, string requestQueuePath, string responseQueuePath)
        {
            ThreadPool.SetMinThreads(100, 100);

            _networkAdapter = new NetworkAdapter(networkInterface);

            _requestQueuePath = requestQueuePath;
            _responseQueuePath = responseQueuePath;

            _mqBll = new MQBLL();
            _mqBll.NewMessageAvailable += new NewMessageEventHandler(_mqBll_NewMessageAvailable);
        }
Пример #36
0
 private static string GetIpv4StringFromNetworkAdapter(string result, NetworkInterface adapter)
 {
     if (adapter == null) return null;
     foreach (UnicastIPAddressInformation ip in adapter.GetIPProperties().UnicastAddresses)
     {
         if (ip.Address.AddressFamily == AddressFamily.InterNetwork)
         {
             result = ip.Address.ToString();
         }
     }
     return result;
 }
Пример #37
0
        private void CheckNetworkInterfaceStatuses(Dictionary <int, NetworkInterfaceHandler> interfaceHandlers)
        {
            lock (interfaceHandlers)
            {
                if (interfaceHandlers != _interfaceHandlers)
                {
                    return;
                }

                HashSet <NetworkInterfaceHandler> handlers       = new HashSet <NetworkInterfaceHandler>(_interfaceHandlers.Values);
                NetworkInterfaceInformation[]     interfaceInfos = NetworkInterfaceInformation.GetAllNetworkInterfaces();
                foreach (NetworkInterfaceInformation interfaceInfo in interfaceInfos)
                {
                    if (interfaceInfo.NetworkInterfaceType == NetworkInterfaceType.Loopback)
                    {
                        continue;
                    }
                    if (interfaceInfo.NetworkInterfaceType == NetworkInterfaceType.Tunnel)
                    {
                        continue;
                    }

                    int index = interfaceInfo.GetIPProperties().GetIPv4Properties().Index;
                    NetworkInterfaceHandler interfaceHandler;
                    _interfaceHandlers.TryGetValue(index, out interfaceHandler);
                    if (interfaceHandler == null)
                    {
                        var networkInterface = new NetworkInterface(interfaceInfo);
                        index            = interfaceInfo.GetIPProperties().GetIPv4Properties().Index;
                        interfaceHandler = new NetworkInterfaceHandler(this, networkInterface);
                        _interfaceHandlers.Add(index, interfaceHandler);
                        OnNetworkInterfaceAdded(networkInterface);
                        interfaceHandler.StartBrowse(_serviceTypes.Select(st => new Name(st.ToLower() + ".local.")));
                    }
                    if (interfaceInfo.OperationalStatus == OperationalStatus.Up)
                    {
                        interfaceHandler.Enable();
                    }
                    else
                    {
                        interfaceHandler.Disable();
                    }
                    handlers.Remove(interfaceHandler);
                }
                foreach (NetworkInterfaceHandler handler in handlers)
                {
                    _interfaceHandlers.Remove(handler.Index);
                    handler.Disable();
                    OnNetworkInterfaceRemoved(handler.NetworkInterface);
                }
            }
        }
        public void AddInterface(NetworkInterface adapter)
        {
            if (adapter.NetworkInterfaceType == NetworkInterfaceType.Tunnel || adapter.NetworkInterfaceType == NetworkInterfaceType.Loopback)
                return;
            if (adapter.OperationalStatus == OperationalStatus.Down)
                return;

                bool found = false;
                foreach (var s in _interfaces){
                    if (s.name == adapter.Name)
                    {
                        found = true;
                    }
                }
                if(found == false){
                    var inf = new StatNetworkItem(adapter.Name);
                     _interfaces.Add(inf);
                    sessionID = DateTime.Now.Ticks;
                }

                foreach (var s in _interfaces){
                    if(s.name == adapter.Name){
                        if (resetAddresses)
                        {
                            s.address = null;
                            IPInterfaceProperties properties = adapter.GetIPProperties();
                            UnicastIPAddressInformationCollection uniCast = properties.UnicastAddresses;
                            foreach (UnicastIPAddressInformation uni in uniCast)
                            {
                                var address = uni.Address.ToString();
                                if (address.Contains("127."))
                                    continue;

                                Match match = Regex.Match(address, @"([0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3})", RegexOptions.IgnoreCase);
                                if (match.Success)
                                {
                                    s.address = address;
                                }
                            }
                        }

                         var ns = new NetworkStatQueue
                         {
                             Upload = adapter.GetIPv4Statistics().BytesSent,
                             Download = adapter.GetIPv4Statistics().BytesReceived,
                             SampleID = historyIndex
                         };
                        s.historyTotals.Enqueue(ns);
                        s.UpdateBandwidth();
                    }
                }
        }
        private bool InterfaceEnabled(NetworkInterface iface)
        {
            if (!excluded.Any() && !included.Any())
                return true;

            if (excluded.Contains(iface.Description))
                return false;

            if (included.Contains(iface.Description))
                return true;

            return false;
        }
Пример #40
0
        /// <summary>
        /// Get the network interface by index
        /// </summary>
        /// <param name="index">Index of the network interface</param>
        /// <returns>Network interface</returns>
        public static NetworkInterface Get(int index)
        {
            int i = 0;

            foreach (NetworkInterface iface in NetworkInterface.GetAllNetworkInterfaces())
            {
                if (iface.NetworkInterfaceType != NetworkInterfaceType.Loopback && i++ == index)
                {
                    return(iface);
                }
            }
            throw new ArgumentOutOfRangeException(nameof(index), "Invalid network interface");
        }
Пример #41
0
        bool IsInterfaceUp(MNetworkInterface inf)
        {
            switch (inf.OperationalStatus)
            {
            case OperationalStatus.Dormant:
            case OperationalStatus.Up:
                return(true);

            default:
                // Android considers 'lo' to be always up
                return(inf.NetworkInterfaceType == NetworkInterfaceType.Loopback);
            }
        }
Пример #42
0
 public void setInterface(int ifaceIndex)
 {
     INTERFAZ = client.Interfaces[ifaceIndex];
     System.Net.NetworkInformation.NetworkInterface[] lista_ethernets = System.Net.NetworkInformation.NetworkInterface.GetAllNetworkInterfaces();
     foreach (NetworkInterface EtherIface in lista_ethernets)
     {
         if (INTERFAZ.InterfaceGuid.CompareTo(new Guid(EtherIface.Id)) == 0)
         {
             IfaceEthernet = EtherIface;
             break;
         }
     }
 }
        public NetworkInterfaceInternal(System.Net.NetworkInformation.NetworkInterface nic)
        {
            if (nic == null)
            {
                return;
            }

            _id            = nic.Id;
            _name          = nic.Name;
            _descr         = nic.Description;
            _interfaceType = nic.NetworkInterfaceType;
            _status        = nic.OperationalStatus;
            _mac           = nic.GetPhysicalAddress().GetAddressBytes();
        }
Пример #44
0
 internal NetworkInterface(NetworkInterfaceInformation info)
 {
     Information = info;
     IPv4Index   = -1;
     IPv6Index   = -1;
     if (info.Supports(NetworkInterfaceComponent.IPv4))
     {
         IPv4Index = info.GetIPProperties().GetIPv4Properties().Index;
     }
     if (info.Supports(NetworkInterfaceComponent.IPv6))
     {
         IPv6Index = info.GetIPProperties().GetIPv6Properties().Index;
     }
     Index = Interlocked.Increment(ref NextIndex);
 }
Пример #45
0
 public static string GetNetworkAdapterId()
 {
     try
     {
         System.Net.NetworkInformation.NetworkInterface[] networkInterfaces = System.Net.NetworkInformation.NetworkInterface.GetAllNetworkInterfaces();
         System.Net.NetworkInformation.NetworkInterface   networkInterface  = ((IEnumerable <System.Net.NetworkInformation.NetworkInterface>)networkInterfaces).FirstOrDefault <System.Net.NetworkInformation.NetworkInterface>((Func <System.Net.NetworkInformation.NetworkInterface, bool>)(i => i.NetworkInterfaceType == NetworkInterfaceType.Wireless80211)) ?? ((IEnumerable <System.Net.NetworkInformation.NetworkInterface>)networkInterfaces).FirstOrDefault <System.Net.NetworkInformation.NetworkInterface>((Func <System.Net.NetworkInformation.NetworkInterface, bool>)(i => i.NetworkInterfaceType == NetworkInterfaceType.Ethernet)) ?? ((IEnumerable <System.Net.NetworkInformation.NetworkInterface>)networkInterfaces).FirstOrDefault <System.Net.NetworkInformation.NetworkInterface>();
         if (networkInterface == null)
         {
             return((string)null);
         }
         string id = networkInterface.Id;
         return(string.IsNullOrEmpty(id) ? (string)null : id);
     }
     catch
     {
         return((string)null);
     }
 }
Пример #46
0
        private void StartBrowsing()
        {
            if (IsBrowsing)
            {
                return;
            }
            IsBrowsing = true;

            if (SynchronizationContext == null)
            {
                SynchronizationContext = SynchronizationContext.Current;
            }

            _interfaceHandlers = new Dictionary <int, NetworkInterfaceHandler>();

            NetworkInterfaceInformation[] interfaceInfos = NetworkInterfaceInformation.GetAllNetworkInterfaces();
            foreach (NetworkInterfaceInformation interfaceInfo in interfaceInfos)
            {
                if (interfaceInfo.NetworkInterfaceType == NetworkInterfaceType.Loopback)
                {
                    continue;
                }
                if (interfaceInfo.NetworkInterfaceType == NetworkInterfaceType.Tunnel)
                {
                    continue;
                }

                var networkInterface = new NetworkInterface(interfaceInfo);
                var e = new InterfaceDetectedEventArgs(networkInterface)
                {
                    Add = true
                };

                OnInterfaceDetect(e);
                if (e.Add)
                {
                    int index = interfaceInfo.GetIPProperties().GetIPv4Properties().Index;
                    _interfaceHandlers.Add(index, new NetworkInterfaceHandler(this, networkInterface));
                }
            }
            NetworkChange.NetworkAddressChanged += CheckNetworkInterfaceStatuses;
            CheckNetworkInterfaceStatuses(null, null);
        }
Пример #47
0
 private void CheckNetworkInterfaceStatuses(object sender, EventArgs e)
 {
     lock (_interfaceHandlers)
     {
         HashSet <NetworkInterfaceHandler> handlers       = new HashSet <NetworkInterfaceHandler>(_interfaceHandlers.Values);
         NetworkInterfaceInformation[]     interfaceInfos = NetworkInterfaceInformation.GetAllNetworkInterfaces();
         foreach (NetworkInterfaceInformation interfaceInfo in interfaceInfos)
         {
             if (interfaceInfo.NetworkInterfaceType == NetworkInterfaceType.Loopback)
             {
                 continue;
             }
             if (interfaceInfo.NetworkInterfaceType == NetworkInterfaceType.Tunnel)
             {
                 continue;
             }
             int index = interfaceInfo.GetIPProperties().GetIPv4Properties().Index;
             NetworkInterfaceHandler interfaceHandler;
             _interfaceHandlers.TryGetValue(index, out interfaceHandler);
             if (interfaceHandler == null)
             {
                 var networkInterface = new NetworkInterface(interfaceInfo);
                 index            = interfaceInfo.GetIPProperties().GetIPv4Properties().Index;
                 interfaceHandler = new NetworkInterfaceHandler(this, networkInterface);
                 _interfaceHandlers.Add(index, interfaceHandler);
             }
             if (interfaceInfo.OperationalStatus == OperationalStatus.Up)
             {
                 interfaceHandler.Enable();
             }
             else
             {
                 interfaceHandler.Disable();
             }
             handlers.Remove(interfaceHandler);
         }
         foreach (NetworkInterfaceHandler handler in handlers)
         {
             handler.Disable();
         }
     }
 }
Пример #48
0
    protected void Page_Load(object sender, EventArgs e)
    {
        System.Net.NetworkInformation.NetworkInterface[]    nics       = System.Net.NetworkInformation.NetworkInterface.GetAllNetworkInterfaces();
        System.Net.NetworkInformation.NetworkInterface      adapter    = nics[0];
        System.Net.NetworkInformation.IPInterfaceProperties properties = adapter.GetIPProperties();
        Startup_Util.UserMac = adapter.GetPhysicalAddress().ToString();


        System.Net.IPHostEntry host;
        host = System.Net.Dns.GetHostByAddress(Request.ServerVariables["REMOTE_HOST"]);
        Startup_Util.UserPC = host.HostName;
        Startup_Util.UserIP = Request.ServerVariables["REMOTE_HOST"];

        Response.Cache.SetCacheability(HttpCacheability.ServerAndNoCache);
        String ST = Startup_Util.DcryptionPWD(Request.QueryString[0].ToString());

        string[] ARY;
        ARY = ST.Split('~');
        string[] ARY1;
        ARY1 = ARY[0].Split('|');

        Startup_Util.SSO_DB            = ARY1[9].ToString();  //SINGLE SIGN ON CONNECTION STRING
        Startup_Util.SPDS_DB           = ARY1[10].ToString(); //SPDS CONNECTION STRING
        Session["EXP_PAGE"]            = ARY1[8].ToString();
        Session["CompleteInformation"] = ARY1[5].ToString() + " | " + ARY1[6].ToString() + " | ";
        Label1.Text         = Session["CompleteInformation"].ToString();
        Session["LOG_CODE"] = ARY1[4].ToString();
        Session["U_NAME"]   = ARY1[5].ToString();

        //I1.Attributes["src"] = "../MasterPage/Default2.aspx";

        if (SSO_Control1.LoginStatus(Session["LOG_CODE"].ToString()) == 0)
        {
            Response.Redirect(Session["EXP_PAGE"].ToString());
        }
        else
        {
            SSO_Control1.GearUp(ARY1[3].ToString(), ARY1[4].ToString());
        }
    }
Пример #49
0
        /// <summary>
        /// Set and/or report the network mask via M553
        /// </summary>
        /// <param name="index">Index of the network interface</param>
        /// <param name="netmask">Subnet mask</param>
        /// <returns>Configuration result</returns>
        public static async Task <string> ManageNetmask(int index, IPAddress netmask)
        {
            NetworkInterface iface = Get(index);

            if (netmask != null)
            {
                return(await DHCP.SetIPAddress(iface.Name, null, netmask, null, null));
            }

            if (iface.OperationalStatus == OperationalStatus.Up)
            {
                UnicastIPAddressInformation ipInfo = (from unicastAddress in iface.GetIPProperties().UnicastAddresses
                                                      where unicastAddress.Address.AddressFamily == AddressFamily.InterNetwork
                                                      select unicastAddress).FirstOrDefault();
                netmask = (ipInfo != null) ? ipInfo.IPv4Mask : IPAddress.Any;
            }
            else
            {
                netmask = await DHCP.GetConfiguredNetmask(iface.Name);
            }
            return($"Net mask: {netmask}");
        }
Пример #50
0
        private System.Net.IPAddress getLocalSameNetworkIP(string deviceIP)
        {
            string ipString = "127.0.0.1";

            System.Net.IPAddress iPAddress = System.Net.IPAddress.Parse(deviceIP);
            System.Net.NetworkInformation.NetworkInterface[] allNetworkInterfaces = System.Net.NetworkInformation.NetworkInterface.GetAllNetworkInterfaces();
            for (int i = 0; i < allNetworkInterfaces.Length; i++)
            {
                System.Net.NetworkInformation.NetworkInterface networkInterface = allNetworkInterfaces[i];
                if (networkInterface.NetworkInterfaceType == System.Net.NetworkInformation.NetworkInterfaceType.Wireless80211 || networkInterface.NetworkInterfaceType == System.Net.NetworkInformation.NetworkInterfaceType.Ethernet)
                {
                    foreach (System.Net.NetworkInformation.UnicastIPAddressInformation current in networkInterface.GetIPProperties().UnicastAddresses)
                    {
                        if (current.Address.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork && current.IPv4Mask != null && (iPAddress.Address & current.IPv4Mask.Address) == (current.Address.Address & current.IPv4Mask.Address))
                        {
                            return(current.Address);
                        }
                    }
                }
            }
            return(System.Net.IPAddress.Parse(ipString));
        }
Пример #51
0
        public NetworkConnectionInfo(NetworkInterface ntwkInterface)
        {
            try
            {
                ntwkInfo = new Dictionary <string, IPAddress[]>();

                if (ntwkInterface == null)
                {
                    return;
                }
                this.nic = new NetworkInterfaceInternal(ntwkInterface);
                var ipProps = ntwkInterface.GetIPProperties();

                foreach (var name in PropertyNames.GetIPAddressPropertyNames())
                {
                    ntwkInfo[name] = GetAddress(name, ipProps);
                }

                foreach (var addr in ipProps.UnicastAddresses)
                {
                    var pre = addr.PrefixOrigin != NetInfo.PrefixOrigin.Manual;
                    var suf = addr.SuffixOrigin != NetInfo.SuffixOrigin.Manual;

                    _autoAssignedAddress = pre && suf;
                    if (_autoAssignedAddress)
                    {
                        break;
                    }
                }

                _dnsSuffix = ipProps.DnsSuffix;
                _initializedSuccessfully = true;
            }
            catch
            {
                _initializedSuccessfully = false;
            }
        }
Пример #52
0
        public void DotNetInterfacesShouldEqualJavaInterfaces()
        {
            List <InterfaceInfo> dotnetInterfaces = GetInfos(MNetworkInterface.GetAllNetworkInterfaces());
            List <InterfaceInfo> javaInterfaces   = GetInfos(JNetworkInterface.NetworkInterfaces);

            Console.WriteLine("Mono interfaces:");
            foreach (InterfaceInfo inf in dotnetInterfaces)
            {
                Console.WriteLine(inf);
            }

            Console.WriteLine("Java interfaces:");
            foreach (InterfaceInfo inf in javaInterfaces)
            {
                Console.WriteLine(inf);
            }

            Assert.IsNotNull(dotnetInterfaces, "#1.1");
            Assert.IsTrue(dotnetInterfaces.Count > 0, "#1.2");

            Assert.IsNotNull(javaInterfaces, "#2.1");
            Assert.IsTrue(javaInterfaces.Count > 0, "#2.2");

            Assert.AreEqual(dotnetInterfaces.Count, javaInterfaces.Count, "#3.1");

            int counter = 4;

            foreach (InterfaceInfo inf in dotnetInterfaces)
            {
                counter++;
                Assert.IsNotNull(inf, String.Format("#{0}.1", counter));
                Assert.IsFalse(String.IsNullOrEmpty(inf.Name), String.Format("#{0}.2", counter));
                Assert.IsTrue(javaInterfaces.Contains(inf), "#{0}.3 ({1} not found in Java interfaces)", counter, inf.Name);
                Console.WriteLine("Interface {0}: passed", inf.Name);
            }
        }
Пример #53
0
        /*SocketAdapter(IPAddress ip) {
         *  this.ip=ip;
         * }*/
        SocketAdapter(NetworkInterface nic, IPAddress ip)
        {
            this.nic = nic;
            this.ip  = ip;
            if (nic.Supports(NetworkInterfaceComponent.IPv4) && ip.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)
            {
                this.basePacketType = PacketReceivedEventArgs.PacketTypes.IPv4Packet;
            }
            else if (nic.Supports(NetworkInterfaceComponent.IPv6) && ip.AddressFamily == System.Net.Sockets.AddressFamily.InterNetworkV6)
            {
                this.basePacketType = PacketReceivedEventArgs.PacketTypes.IPv6Packet;
            }
            else//use IPv4 as default
            {
                this.basePacketType = PacketReceivedEventArgs.PacketTypes.IPv4Packet;
            }

            /*
             * UnicastIPAddressInformationCollection ipAddressCollection=nic.GetIPProperties().UnicastAddresses;
             * if (ipAddressCollection.Count > 0)
             *  this.ip = ipAddressCollection[0].Address;
             * else this.ip = IPAddress.None;
             * */
        }
Пример #54
0
        async Task NetworkRequestAsync(byte[] requestBytes,
                                       TimeSpan scanTime,
                                       int retries,
                                       int retryDelayMilliseconds,
                                       Action <string, byte[]> onResponse,
                                       System.Net.NetworkInformation.NetworkInterface adapter,
                                       CancellationToken cancellationToken)
        {
            // http://stackoverflow.com/questions/2192548/specifying-what-network-interface-an-udp-multicast-should-go-to-in-net

#if !XAMARIN
            if (!adapter.GetIPProperties().MulticastAddresses.Any())
            {
                return; // most of VPN adapters will be skipped
            }
#endif
            if (!adapter.SupportsMulticast)
            {
                return; // multicast is meaningless for this type of connection
            }
            if (OperationalStatus.Up != adapter.OperationalStatus)
            {
                return; // this adapter is off or not connected
            }
            if (adapter.NetworkInterfaceType == NetworkInterfaceType.Loopback)
            {
                return; // strip out loopback addresses
            }
            var p = adapter.GetIPProperties().GetIPv4Properties();
            if (null == p)
            {
                return; // IPv4 is not configured on this adapter
            }
            var ipv4Address = adapter.GetIPProperties().UnicastAddresses
                              .FirstOrDefault(ua => ua.Address.AddressFamily == AddressFamily.InterNetwork)?.Address;

            if (ipv4Address == null)
            {
                return; // could not find an IPv4 address for this adapter
            }
            var ifaceIndex = p.Index;

            Debug.WriteLine($"Scanning on iface {adapter.Name}, idx {ifaceIndex}, IP: {ipv4Address}");

            using (var client = new UdpClient())
            {
                for (var i = 0; i < retries; i++)
                {
#if ANDROID
                    var mlock = wifi.CreateMulticastLock("Zeroconf lock");
#endif
                    try
                    {
#if ANDROID
                        mlock.Acquire();
#endif
                        client.Client.SetSocketOption(SocketOptionLevel.IP,
                                                      SocketOptionName.MulticastInterface,
                                                      IPAddress.HostToNetworkOrder(ifaceIndex));



                        client.ExclusiveAddressUse = false;
                        client.Client.SetSocketOption(SocketOptionLevel.Socket,
                                                      SocketOptionName.ReuseAddress,
                                                      true);
                        client.Client.SetSocketOption(SocketOptionLevel.Socket,
                                                      SocketOptionName.ReceiveTimeout,
                                                      scanTime.Milliseconds);
                        client.ExclusiveAddressUse = false;


                        var localEp = new IPEndPoint(IPAddress.Any, 5353);

                        Debug.WriteLine($"Attempting to bind to {localEp} on adapter {adapter.Name}");
                        client.Client.Bind(localEp);
                        Debug.WriteLine($"Bound to {localEp}");

                        var multicastAddress = IPAddress.Parse("224.0.0.251");
                        var multOpt          = new MulticastOption(multicastAddress, ifaceIndex);
                        client.Client.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.AddMembership, multOpt);


                        Debug.WriteLine("Bound to multicast address");

                        // Start a receive loop
                        var shouldCancel = false;
                        var recTask      = Task.Run(async
                                                        () =>
                        {
                            try
                            {
                                while (!shouldCancel)
                                {
                                    var res = await client.ReceiveAsync()
                                              .ConfigureAwait(false);
                                    onResponse(res.RemoteEndPoint.Address.ToString(), res.Buffer);
                                }
                            }
                            catch (ObjectDisposedException)
                            {
                            }
                        }, cancellationToken);

                        var broadcastEp = new IPEndPoint(IPAddress.Parse("224.0.0.251"), 5353);
                        Debug.WriteLine($"About to send on iface {adapter.Name}");
                        await client.SendAsync(requestBytes, requestBytes.Length, broadcastEp)
                        .ConfigureAwait(false);

                        Debug.WriteLine($"Sent mDNS query on iface {adapter.Name}");


                        // wait for responses
                        await Task.Delay(scanTime, cancellationToken)
                        .ConfigureAwait(false);

                        shouldCancel = true;
#if CORECLR
                        client.Dispose();
#else
                        client.Close();
#endif

                        Debug.WriteLine("Done Scanning");


                        await recTask.ConfigureAwait(false);

                        return;
                    }
                    catch (Exception e)
                    {
                        Debug.WriteLine($"Execption with network request, IP {ipv4Address}\n: {e}");
                        if (i + 1 >= retries) // last one, pass underlying out
                        {
                            throw;
                        }
                    }
                    finally
                    {
#if ANDROID
                        mlock.Release();
#endif
                    }

                    await Task.Delay(retryDelayMilliseconds, cancellationToken).ConfigureAwait(false);
                }
            }
        }
Пример #55
0
        public SystemNetworkInterface(System.Net.NetworkInformation.NetworkInterface networkInterface)
        {
            Ensure.NotNull(networkInterface, nameof(networkInterface));

            _networkInterface = networkInterface;
        }
Пример #56
0
        public async Task NetworkRequestAsync(byte[] requestBytes,
                                              TimeSpan scanTime,
                                              int retries,
                                              int retryDelayMilliseconds,
                                              Action <IPAddress, byte[]> onResponse,
                                              System.Net.NetworkInformation.NetworkInterface adapter,
                                              CancellationToken cancellationToken)
        {
            // http://stackoverflow.com/questions/2192548/specifying-what-network-interface-an-udp-multicast-should-go-to-in-net

            // Xamarin doesn't support this
            //if (!adapter.GetIPProperties().MulticastAddresses.Any())
            //    return; // most of VPN adapters will be skipped

            if (!adapter.SupportsMulticast)
            {
                return; // multicast is meaningless for this type of connection
            }
            if (OperationalStatus.Up != adapter.OperationalStatus)
            {
                return; // this adapter is off or not connected
            }
            if (adapter.NetworkInterfaceType == NetworkInterfaceType.Loopback)
            {
                return; // strip out loopback addresses
            }
            var p = adapter.GetIPProperties().GetIPv4Properties();

            if (null == p)
            {
                return; // IPv4 is not configured on this adapter
            }
            var ipv4Address = adapter.GetIPProperties().UnicastAddresses
                              .FirstOrDefault(ua => ua.Address.AddressFamily == AddressFamily.InterNetwork)?.Address;

            if (ipv4Address == null)
            {
                return; // could not find an IPv4 address for this adapter
            }
            var ifaceIndex = p.Index;

            Debug.WriteLine($"Scanning on iface {adapter.Name}, idx {ifaceIndex}, IP: {ipv4Address}");


            using (var client = new UdpClient())
            {
                for (var i = 0; i < retries; i++)
                {
                    try
                    {
                        var socket = client.Client;

                        if (socket.IsBound)
                        {
                            continue;
                        }

                        socket.SetSocketOption(SocketOptionLevel.IP,
                                               SocketOptionName.MulticastInterface,
                                               IPAddress.HostToNetworkOrder(ifaceIndex));



                        client.ExclusiveAddressUse = false;
                        socket.SetSocketOption(SocketOptionLevel.Socket,
                                               SocketOptionName.ReuseAddress,
                                               true);
                        socket.SetSocketOption(SocketOptionLevel.Socket,
                                               SocketOptionName.ReceiveTimeout,
                                               (int)scanTime.TotalMilliseconds);
                        client.ExclusiveAddressUse = false;


                        var localEp = new IPEndPoint(IPAddress.Any, 5353);

                        Debug.WriteLine($"Attempting to bind to {localEp} on adapter {adapter.Name}");
                        socket.Bind(localEp);
                        Debug.WriteLine($"Bound to {localEp}");

                        var multicastAddress = IPAddress.Parse("224.0.0.251");
                        var multOpt          = new MulticastOption(multicastAddress, ifaceIndex);
                        socket.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.AddMembership, multOpt);


                        Debug.WriteLine("Bound to multicast address");


                        // Start a receive loop
                        var shouldCancel = false;
                        var recTask      = Task.Run(async
                                                        () =>
                        {
                            try
                            {
                                while (!Volatile.Read(ref shouldCancel))
                                {
                                    var res = await client.ReceiveAsync()
                                              .ConfigureAwait(false);

                                    onResponse(res.RemoteEndPoint.Address, res.Buffer);
                                }
                            }
                            catch when(Volatile.Read(ref shouldCancel))
                            {
                                // If we're canceling, eat any exceptions that come from here
                            }
                        }, cancellationToken);

                        var broadcastEp = new IPEndPoint(IPAddress.Parse("224.0.0.251"), 5353);

                        Debug.WriteLine($"About to send on iface {adapter.Name}");
                        await client.SendAsync(requestBytes, requestBytes.Length, broadcastEp)
                        .ConfigureAwait(false);

                        Debug.WriteLine($"Sent mDNS query on iface {adapter.Name}");


                        // wait for responses
                        await Task.Delay(scanTime, cancellationToken)
                        .ConfigureAwait(false);

                        Volatile.Write(ref shouldCancel, true);

                        ((IDisposable)client).Dispose();

                        Debug.WriteLine("Done Scanning");


                        await recTask.ConfigureAwait(false);

                        return;
                    }
                    catch (Exception e)
                    {
                        Debug.WriteLine($"Execption with network request, IP {ipv4Address}\n: {e}");
                        if (i + 1 >= retries) // last one, pass underlying out
                        {
                            // Ensure all inner info is captured
                            ExceptionDispatchInfo.Capture(e).Throw();
                            throw;
                        }
                    }

                    await Task.Delay(retryDelayMilliseconds, cancellationToken).ConfigureAwait(false);
                }
            }
        }
Пример #57
0
        Task ListenForAnnouncementsAsync(System.Net.NetworkInformation.NetworkInterface adapter, Action <AdapterInformation, string, byte[]> callback, CancellationToken cancellationToken)
        {
            return(Task.Factory.StartNew(async() =>
            {
                var ipv4Address = adapter.GetIPProperties().UnicastAddresses
                                  .First(ua => ua.Address.AddressFamily == AddressFamily.InterNetwork)?.Address;

                if (ipv4Address == null)
                {
                    return;
                }

                var ifaceIndex = adapter.GetIPProperties().GetIPv4Properties()?.Index;
                if (ifaceIndex == null)
                {
                    return;
                }

                Debug.WriteLine($"Scanning on iface {adapter.Name}, idx {ifaceIndex}, IP: {ipv4Address}");

                using (var client = new UdpClient())
                {
                    var socket = client.Client;
                    socket.SetSocketOption(SocketOptionLevel.IP,
                                           SocketOptionName.MulticastInterface,
                                           IPAddress.HostToNetworkOrder(ifaceIndex.Value));

                    socket.SetSocketOption(SocketOptionLevel.Socket,
                                           SocketOptionName.ReuseAddress,
                                           true);
                    client.ExclusiveAddressUse = false;


                    var localEp = new IPEndPoint(IPAddress.Any, 5353);
                    socket.Bind(localEp);

                    var multicastAddress = IPAddress.Parse("224.0.0.251");
                    var multOpt = new MulticastOption(multicastAddress, ifaceIndex.Value);
                    socket.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.AddMembership, multOpt);


                    cancellationToken.Register((() =>
                    {
                        ((IDisposable)client).Dispose();
                    }));


                    while (!cancellationToken.IsCancellationRequested)
                    {
                        try
                        {
                            var packet = await client.ReceiveAsync()
                                         .ConfigureAwait(false);
                            try
                            {
                                callback(new AdapterInformation(ipv4Address.ToString(), adapter.Name), packet.RemoteEndPoint.Address.ToString(), packet.Buffer);
                            }
                            catch (Exception ex)
                            {
                                Debug.WriteLine($"Callback threw an exception: {ex}");
                            }
                        }
                        catch when(cancellationToken.IsCancellationRequested)
                        {
                            // eat any exceptions if we've been cancelled
                        }
                    }


                    Debug.WriteLine($"Done listening for mDNS packets on {adapter.Name}, idx {ifaceIndex}, IP: {ipv4Address}.");

                    cancellationToken.ThrowIfCancellationRequested();
                }
            }, cancellationToken, TaskCreationOptions.LongRunning, TaskScheduler.Default).Unwrap());
        }
Пример #58
0
 static bool IsLoopbackInterface(MNetworkInterface inf)
 {
     // Android 30 will not tell us the interface type if the app targets API 30, we need to look at the
     // name then.
     return(inf.NetworkInterfaceType == NetworkInterfaceType.Loopback || String.Compare("lo", inf.Name, StringComparison.OrdinalIgnoreCase) == 0);
 }
Пример #59
0
 public NetworkInterface(System.Net.NetworkInformation.NetworkInterface nic, UnicastIPAddressInformation unicasIp)
 {
     this.Networkinterface = nic;
     this.IP = unicasIp;
 }
Пример #60
0
        /// <summary>
        /// Manage the given network interface via M552
        /// </summary>
        /// <param name="index">Index of the network interface</param>
        /// <param name="pParam">P parameter</param>
        /// <param name="sParam">S parameter</param>
        /// <returns>Configuration result</returns>
        public static async Task <Message> SetConfig(int index, CodeParameter pParam, CodeParameter sParam)
        {
            NetworkInterface iface  = Get(index);
            StringBuilder    result = new();

            if (iface.Name.StartsWith('w'))
            {
                // WiFi interface
                if (sParam == null)
                {
                    // Report the status only if no valid S parameter is given
                    await Report(result, iface, index);
                }
                else if (sParam <= 0 || sParam > 2)
                {
                    // Disable WiFi services
                    result.AppendLine(await AccessPoint.Stop());
                    result.AppendLine(await WPA.Stop());

                    // Disable WiFi adapter
                    string linkResult = await Command.Execute("/usr/sbin/ip", $"link set {iface.Name} down");

                    result.AppendLine(linkResult);
                }
                else if (sParam == 1)
                {
                    // Is there a wpa_supplicant.conf?
                    if (!File.Exists("/etc/wpa_supplicant/wpa_supplicant.conf"))
                    {
                        return(new Message(MessageType.Error, "No WiFi configuration found, use M587 to configure at least one SSID"));
                    }

                    // No longer in AP mode
                    result.AppendLine(await AccessPoint.Stop());

                    // Disable the adapter
                    string disableResult = await Command.Execute("/usr/sbin/ip", $"link set {iface.Name} down");

                    result.AppendLine(disableResult);

                    // Start station mode
                    result.AppendLine(await WPA.Start());

                    // Enable the adapter again
                    string enableResult = await Command.Execute("/usr/sbin/ip", $"link set {iface.Name} up");

                    result.AppendLine(enableResult);

                    // Connect to the given SSID (if applicable)
                    if (pParam != null)
                    {
                        // Find the network index
                        string networkList = await Command.Execute("/usr/sbin/wpa_cli", "list_networks");

                        Regex ssidRegex = new($"^(\\d+)\\s+{Regex.Escape(sParam)}\\W", RegexOptions.IgnoreCase);

                        int networkIndex = -1;
                        using (StringReader reader = new(networkList))
                        {
                            do
                            {
                                string line = await reader.ReadLineAsync();

                                if (line == null)
                                {
                                    break;
                                }

                                Match match = ssidRegex.Match(line);
                                if (match.Success)
                                {
                                    networkIndex = int.Parse(match.Groups[1].Value);
                                    break;
                                }
                            }while (!Program.CancellationToken.IsCancellationRequested);
                        }
                        if (networkIndex == -1)
                        {
                            return(new Message(MessageType.Error, "SSID could not be found, use M587 to configure it first"));
                        }

                        // Select it
                        string selectResult = await Command.Execute("/usr/sbin/wpa_cli", $"-i {iface.Name} select_network {networkIndex}");

                        if (selectResult.Trim() != "OK")
                        {
                            result.AppendLine(selectResult);
                        }
                    }
                    // else wpa_supplicant will connect to the next available network
                }
                else if (sParam == 2)
                {
                    // Are the required config files present?
                    if (!File.Exists("/etc/hostapd/wlan0.conf"))
                    {
                        return(new Message(MessageType.Error, "No hostapd configuration found, use M589 to configure the access point first"));
                    }
                    if (!File.Exists("/etc/dnsmasq.conf"))
                    {
                        return(new Message(MessageType.Error, "No dnsmasq configuration found, use M589 to configure the access point first"));
                    }

                    // Is there at least one DHCP profile for AP mode?
                    if (!await DHCP.IsAPConfigured())
                    {
                        return(new Message(MessageType.Error, "No access point configuration found. Use M587 to configure it first"));
                    }

                    // No longer in station mode
                    result.AppendLine(await WPA.Stop());

                    // Disable the adapter
                    string disableResult = await Command.Execute("/usr/sbin/ip", $"link set {iface.Name} down");

                    result.AppendLine(disableResult);

                    // Start AP mode. This will enable the adapter too
                    result.AppendLine(await AccessPoint.Start());
                }
            }
            else
            {
                // Ethernet interface
                if (pParam != null)
                {
                    // Set IP address
                    IPAddress ip        = IPAddress.Parse(pParam);
                    string    setResult = await DHCP.SetIPAddress(iface.Name, ip, null, null, null);

                    result.AppendLine(setResult);
                }

                if (sParam != null && (iface.OperationalStatus != OperationalStatus.Up) != sParam)
                {
                    // Enable or disable the adapter if required
                    result.AppendLine(await Command.Execute("/usr/sbin/ip", $"link set {iface.Name} {(sParam ? "up" : "down")}"));
                }
            }
            return(new Message(MessageType.Success, result.ToString().Trim()));
        }