Ejemplo n.º 1
0
 public IpAddressSetting(IPInterfaceProperties interfaceProperties, UnicastIPAddressInformation unicastIPAddressInformation)
 {
     IsDhcpEnabled  = interfaceProperties.DhcpServerAddresses.Count != 0;
     Address        = new IpV4Address(unicastIPAddressInformation.Address);
     IPv4Mask       = new IpV4Address(unicastIPAddressInformation.IPv4Mask);
     GatewayAddress = new IpV4Address(interfaceProperties.GatewayAddresses[0].Address);
 }
Ejemplo n.º 2
0
        private static IPAddress GetLocalIp(string adapterName)
        {
            // return IPAddress.Parse("127.0.0.1");
            UnicastIPAddressInformation unicastIPAddressInformation = NetworkInterface
                                                                      .GetAllNetworkInterfaces()
                                                                      .Where(i => i.Name == adapterName)
                                                                      .SelectMany(i => i.GetIPProperties().UnicastAddresses)
                                                                      .FirstOrDefault(i =>
                                                                                      //i.PrefixOrigin != PrefixOrigin.WellKnown
                                                                                      //&&
                                                                                      i.Address.AddressFamily.Equals(AddressFamily.InterNetwork) &&
                                                                                      !IPAddress.IsLoopback(i.Address) &&
                                                                                      i.Address != IPAddress.None);

            IPAddress localAddr = null;

            if (unicastIPAddressInformation != null)
            {
                localAddr = unicastIPAddressInformation.Address;
            }

            if (localAddr == null)
            {
                throw new Exception($"Unable to find local address for adapter {adapterName}.");
            }

            return(localAddr);
        }
Ejemplo n.º 3
0
        /// <summary>
        /// 获取可上网的本机IP(剔除虚拟机的IP)
        /// </summary>
        /// <returns></returns>
        public static string GetLocalIPAddress()
        {
            string           result           = null;
            NetworkInterface networkInterface = null;

            try
            {
                networkInterface = GetNetworkInterface();
                if (networkInterface != null)
                {
                    IPInterfaceProperties ip = networkInterface.GetIPProperties();
                    UnicastIPAddressInformationCollection ipCollection = ip.UnicastAddresses;
                    UnicastIPAddressInformation           unicastIPAddressInformation = ipCollection.FirstOrDefault(w => w.Address.AddressFamily == AddressFamily.InterNetwork);
                    if (unicastIPAddressInformation == null)
                    {
                        unicastIPAddressInformation = ipCollection.FirstOrDefault(w => w.Address.AddressFamily == AddressFamily.InterNetworkV6);
                        result = unicastIPAddressInformation.Address.MapToIPv4().ToString();
                    }
                    else
                    {
                        result = unicastIPAddressInformation.Address.ToString();
                    }
                }
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine(ex);
            }
            return(result);
        }
Ejemplo n.º 4
0
        public static IPAddress CalculateNetwork(this UnicastIPAddressInformation addr)
        {
            // The mask will be null in some scenarios, like a dhcp address 169.254.x.x
            if (addr.IPv4Mask == null)
            {
                return(null);
            }

            var ip   = addr.Address.GetAddressBytes();
            var mask = new byte[4];

            try
            {
                mask = addr.IPv4Mask.GetAddressBytes();
            }
            catch (System.Reflection.TargetInvocationException) // Mono
            {
                mask = new byte[] { 255, 255, 255, 0 };
            }

            var result = new Byte[4];

            for (int i = 0; i < 4; ++i)
            {
                result[i] = (Byte)(ip[i] & mask[i]);
            }

            return(new IPAddress(result));
        }
Ejemplo n.º 5
0
        private void LocalInterfaceCacheHandler(object sender, EventArgs e)
        {
            Logger.Info?.Print(LogClass.ServiceNifm, $"NetworkAddress changed, invalidating cached data.");

            _targetPropertiesCache  = null;
            _targetAddressInfoCache = null;
        }
Ejemplo n.º 6
0
        static Result <string> GetCidrIpFromWindowsIpAddressInformation(UnicastIPAddressInformation ipInfo)
        {
            var ipAddress       = ipInfo.Address;
            var networkBitCount = ipInfo.PrefixLength;

            return(Result.Ok(GetCidrIpFromIpAddressAndNetworkBitCount(ipAddress, networkBitCount)));
        }
Ejemplo n.º 7
0
        /// <summary>
        /// UnicastIPAddressInformation.IPv4Mask is not implemented in Xamarin. This method sits in a partial class definition
        /// on each native platform and retrieves the netmask in whatever way it can be done for each platform.
        /// </summary>
        /// <param name="ip"></param>
        /// <returns></returns>
        protected static IPAddress GetSubnetMask(UnicastIPAddressInformation ip)
        {
            // short circuit on null ip.
            if (ip == null)
            {
                return(null);
            }

            // TODO: Use native java network library rather than incomplete mono/.NET implementation:
            // Move this into CommsInterface.cs and call once rather than iterating all adapters for each GetSubnetMaskCall.
            var interfaces = NetworkInterface.NetworkInterfaces.GetEnumerable <NetworkInterface>().ToList();
            var interfacesWithIPv4Addresses = interfaces
                                              .Where(ni => ni.InterfaceAddresses != null)
                                              .SelectMany(ni => ni.InterfaceAddresses
                                                          .Where(a => a.Address != null && a.Address.HostAddress != null)
                                                          .Select(a => new { NativeInterface = ni, Address = a }))
                                              .ToList();

            var ipAddress = ip.Address.ToString();

            // match the droid interface with the NetworkInterface interface on the IpAddress string
            var match = interfacesWithIPv4Addresses.FirstOrDefault(ni => ni.Address.Address.HostAddress == ipAddress);

            // no match, no good
            if (match == null)
            {
                return(null);
            }

            // use the network prefix length to calculate the subnet address
            var networkPrefixLength = match.Address.NetworkPrefixLength;
            var netMask             = AndroidNetworkExtensions.GetSubnetAddress(ipAddress, networkPrefixLength);

            return(IPAddress.Parse(netMask));
        }
        /// <summary>Gets the local broadcast address for the specified <see cref="UnicastIPAddressInformation" />.</summary>
        /// <param name="address">Address information.</param>
        /// <param name="subnet">Subnet length. (Required for ipv6 on framework &lt;= 4.0).</param>
        /// <returns>Returns a local broadcast address.</returns>
        public static IPAddress GetBroadcastAddress(this UnicastIPAddressInformation address, int subnet = -1)
        {
            if (address.Address.AddressFamily == AddressFamily.InterNetwork)
            {
                if (subnet > -1)
                {
                    return(GetBroadcastAddress(address.Address, subnet));
                }

                return(GetBroadcastAddress(address.Address, address.IPv4Mask));
            }

            if (address.Address.AddressFamily == AddressFamily.InterNetworkV6)
            {
                if (subnet > -1)
                {
                    return(GetBroadcastAddress(address.Address, subnet));
                }
#if NET20 || NET35 || NET40
                throw new NotSupportedException("Prefixlength unknown, subnet length is required! (Use >= net 4.5, netstandard 2.0)");
#else
                return(GetBroadcastAddress(address.Address, address.PrefixLength));
#endif
            }

            throw new NotSupportedException($"AddressFamily {address.Address.AddressFamily} is not supported!");
        }
Ejemplo n.º 9
0
        private void Button_scan_Click(object sender, EventArgs e)
        {
            button_scan.Enabled = false;

            UnicastIPAddressInformation ipInfo = ((EthernetInterface)box_interface.SelectedValue).IP;
            IPAddress host = ipInfo.Address;

            (IPAddress start, IPAddress end, int count) = NetworkManager.GetSubnetRange(host, ipInfo.IPv4Mask);

            scanEvent = new CountdownEvent(count);

            panel_list.Controls.Clear();
            panel_main.Controls.Clear();
            WaitPanel panel = new WaitPanel(ref scanEvent);

            panel.Dock = DockStyle.Fill;
            panel_main.Controls.Add(panel);

            IPAddress ip = start;

            while (!ip.Equals(end))
            {
                ThreadPool.QueueUserWorkItem(TestModule, ip);
                ip = NetworkManager.NextAddress(ip);
            }
        }
Ejemplo n.º 10
0
        string GetInterfaceAddress(string interfaceIndex)
        {
            UnicastIPAddressInformation result = null;

            foreach (var networkInterface in NetworkInterface.GetAllNetworkInterfaces())
            {
                try
                {
                    var ipProperties = networkInterface.GetIPProperties();
                    var prop         = ipProperties.GetIPv4Properties();

                    if (prop.Index.ToString() == interfaceIndex)
                    {
                        result = ipProperties.UnicastAddresses.FirstOrDefault(item => item.Address.AddressFamily == AddressFamily.InterNetwork);
                        break;
                    }
                }
                catch (Exception)
                {
                }
            }

            if (result == null)
            {
                return("127.0.0.1");
            }

            return(result.Address.ToString());
        }
Ejemplo n.º 11
0
 private async void send_udp_broadcast()
 {
     while (true)
     {
         try
         {
             UdpClient client = new UdpClient();
             UnicastIPAddressInformation uni_info = get_unicast_info();
             if (uni_info != null)
             {
                 IPAddress  broad_ip = GetBroadcastAddress(uni_info.Address, uni_info.IPv4Mask);
                 IPEndPoint ip       = new IPEndPoint(broad_ip, 2601);
                 byte[]     bytes    = Encoding.ASCII.GetBytes(G_pcname);
                 client.Send(bytes, bytes.Length, ip);
                 Debug.WriteLine("sending to broadcast ip " + broad_ip.ToString());
             }
         }
         catch (Exception e)
         {
             Debug.WriteLine(" Sending udp broadcast failed at " + e.Message);
         }
         finally
         {
             await Task.Delay(2000);
         }
     }
 }
Ejemplo n.º 12
0
        public static async Task WakeOnLan(string macAddress)
        {
            byte[] magicPacket = BuildMagicPacket(macAddress);
            foreach (NetworkInterface networkInterface in NetworkInterface.GetAllNetworkInterfaces().Where((n) =>
                                                                                                           n.NetworkInterfaceType != NetworkInterfaceType.Loopback && n.OperationalStatus == OperationalStatus.Up))
            {
                IPInterfaceProperties iPInterfaceProperties = networkInterface.GetIPProperties();
                foreach (MulticastIPAddressInformation multicastIPAddressInformation in iPInterfaceProperties.MulticastAddresses)
                {
                    IPAddress multicastIpAddress = multicastIPAddressInformation.Address;
                    if (multicastIpAddress.ToString().StartsWith("ff02::1%", StringComparison.OrdinalIgnoreCase)) // Ipv6: All hosts on LAN (with zone index)
                    {
                        UnicastIPAddressInformation unicastIPAddressInformation = iPInterfaceProperties.UnicastAddresses.Where((u) =>
                                                                                                                               u.Address.AddressFamily == AddressFamily.InterNetworkV6 && !u.Address.IsIPv6LinkLocal).FirstOrDefault();
                        if (unicastIPAddressInformation != null)
                        {
                            await SendWakeOnLan(unicastIPAddressInformation.Address, multicastIpAddress, magicPacket);

                            break;
                        }
                    }
                    else if (multicastIpAddress.ToString().Equals("224.0.0.1")) // Ipv4: All hosts on LAN
                    {
                        UnicastIPAddressInformation unicastIPAddressInformation = iPInterfaceProperties.UnicastAddresses.Where((u) =>
                                                                                                                               u.Address.AddressFamily == AddressFamily.InterNetwork && !iPInterfaceProperties.GetIPv4Properties().IsAutomaticPrivateAddressingActive).FirstOrDefault();
                        if (unicastIPAddressInformation != null)
                        {
                            await SendWakeOnLan(unicastIPAddressInformation.Address, multicastIpAddress, magicPacket);

                            break;
                        }
                    }
                }
            }
        }
Ejemplo n.º 13
0
        /// <summary>
        /// UnicastIPAddressInformation.IPv4Mask is not implemented in Xamarin. This method sits in a partial class definition
        /// on each native platform and retrieves the netmask in whatever way it can be done for each platform.
        /// </summary>
        /// <param name="ip"></param>
        /// <returns></returns>
        protected static IPAddress GetSubnetMask(UnicastIPAddressInformation ip)
        {
            var nativeInterfaceInfo = NetInfo.GetInterfaceInfo();
            var match = nativeInterfaceInfo.FirstOrDefault(ni => ni != null && ni.Address != null && ip != null && ip.Address != null && Equals(ni.Address, ip.Address));

            return(match != null ? match.Netmask : null);
        }
Ejemplo n.º 14
0
        private IPAddress GetSubnetMask(IPAddress address)
        {
            NetworkInterface[]          Interfaces = NetworkInterface.GetAllNetworkInterfaces();
            UnicastIPAddressInformation info       = null;

            foreach (NetworkInterface Interface in Interfaces)
            {
                if (Interface.NetworkInterfaceType == NetworkInterfaceType.Loopback ||
                    !(Interface.OperationalStatus == OperationalStatus.Up))
                {
                    continue;
                }
                Console.WriteLine(Interface.Description);
                UnicastIPAddressInformationCollection UnicastIPInfoCol = Interface.GetIPProperties().UnicastAddresses;
                foreach (UnicastIPAddressInformation UnicatIPInfo in UnicastIPInfoCol)
                {
                    if (UnicatIPInfo.Address.ToString() == address.ToString())
                    {
                        Console.WriteLine("\tIP Address is {0}", UnicatIPInfo.Address);
                        Console.WriteLine("\tSubnet Mask is {0}", UnicatIPInfo.IPv4Mask);
                        info = UnicatIPInfo;
                    }
                }
            }


            return(info.IPv4Mask);
        }
Ejemplo n.º 15
0
        //get local ip address
        public UnicastIPAddressInformation get_unicast_info()
        {
            IPAddress[] host;
            UnicastIPAddressInformation localIP = null;

            host = Dns.GetHostAddresses(Dns.GetHostName());

            //if(G_socket!=null)
            //Debug.WriteLine(G_socket.LocalEndPoint.ToString());

            foreach (NetworkInterface nic in NetworkInterface.GetAllNetworkInterfaces())
            {
                foreach (UnicastIPAddressInformation IP_info in nic.GetIPProperties().UnicastAddresses)
                {
                    if (IP_info.Address.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)
                    {
                        if (!IPAddress.IsLoopback(IP_info.Address) && host.Contains(IP_info.Address) &&
                            !nic.Name.ToLower().Contains("loopback"))
                        {
                            localIP = IP_info;
                        }
                    }
                }
            }

            return(localIP);
        }
Ejemplo n.º 16
0
 private void SendInterfaceBroadcast(UnicastIPAddressInformation info, byte[] packet)
 {
     switch (info.Address.AddressFamily)
     {
     case AddressFamily.InterNetwork:
     {
         IPAddress addr = info.GetBroadcastAddress();
         if (GetError(addr) >= 5)
         {
             return;
         }
         try
         {
             Trace.WriteLine($"Send broadcast packet to {addr}");
             sock?.SendTo(packet, new IPEndPoint(addr, Port));
         }
         catch (Exception ex)
         {
             this.LogWarning(ex, "Error while sending broadcast at {0}:{1}", addr, Port);
             IncError(addr);
         }
         break;
     }
     }
 }
Ejemplo n.º 17
0
 /// <summary>
 /// Works around a method that was not implemented in some mono versions.
 /// </summary>
 /// <param name="addressInfo"></param>
 private void AddV4AddressMono(UnicastIPAddressInformation addressInfo)
 {
     if (monoIPv4MaskTestState == 0)
     {
         AddV4Address(addressInfo.Address.GetAddressBytes(), new byte[] { 255, 255, 255, 0 });
     }
     else if (monoIPv4MaskTestState == 1)
     {
         AddV4Address(addressInfo.Address.GetAddressBytes(), addressInfo.IPv4Mask.GetAddressBytes());
     }
     else
     {
         if (monoIPv4MaskTestState != 0)
         {
             try
             {
                 AddV4Address(addressInfo.Address.GetAddressBytes(), addressInfo.IPv4Mask.GetAddressBytes());
                 monoIPv4MaskTestState = 1;
                 return;
             }
             catch (NotImplementedException ex)
             {
                 Logger.Debug(ex, "Your mono version is old, and does not support retrieving IPv4 Masks for your network interfaces. Assuming 255.255.255.0 from now on.");
                 monoIPv4MaskTestState = 0;
                 AddV4Address(addressInfo.Address.GetAddressBytes(), new byte[] { 255, 255, 255, 0 });
             }
         }
     }
 }
Ejemplo n.º 18
0
        /// <summary>
        /// 获取本地IP地址
        /// </summary>
        /// <returns></returns>
        public static string GetLocalIp()
        {
            UnicastIPAddressInformation mostSuitableIp = null;
            var networkInterfaces = NetworkInterface.GetAllNetworkInterfaces();

            foreach (var network in networkInterfaces)
            {
                if (network.OperationalStatus != OperationalStatus.Up)
                {
                    continue;
                }
                var properties = network.GetIPProperties();
                if (properties.GatewayAddresses.Count == 0)
                {
                    continue;
                }

                foreach (var address in properties.UnicastAddresses)
                {
                    if (address.Address.AddressFamily != AddressFamily.InterNetwork)
                    {
                        continue;
                    }
                    if (IPAddress.IsLoopback(address.Address))
                    {
                        continue;
                    }
                    return(address.Address.ToString());
                }
            }

            return(mostSuitableIp != null
                ? mostSuitableIp.Address.ToString()
                : "");
        }
Ejemplo n.º 19
0
        /// <summary>
        /// 获取本机所有的IP地址
        /// </summary>
        /// <returns></returns>
        public static List <string> GetAllIpAddresses()
        {
            var           interfaces = GetAllNetWorkInterfaces();
            List <string> addresses  = new List <string>();

            foreach (var f in interfaces)
            {
                IPInterfaceProperties ip = f.GetIPProperties();
                UnicastIPAddressInformationCollection ipCollection = ip.UnicastAddresses;
                UnicastIPAddressInformation           unicastIpAddressInformation = ipCollection.FirstOrDefault(w => w.Address.AddressFamily == AddressFamily.InterNetwork);
                if (unicastIpAddressInformation == null)
                {
                    unicastIpAddressInformation = ipCollection.FirstOrDefault(w => w.Address.AddressFamily == AddressFamily.InterNetworkV6);
                    if (unicastIpAddressInformation != null)
                    {
                        var ipV4Address = unicastIpAddressInformation.Address.MapToIPv4().ToString();
                        addresses.Add(ipV4Address);
                    }
                }
                else
                {
                    var address = unicastIpAddressInformation.Address.ToString();
                    addresses.Add(address);
                }
            }
            return(addresses);
        }
Ejemplo n.º 20
0
        public string GetLocalIP()
        {
            UnicastIPAddressInformation mostSuitableIp = null;

            var networkInterfaces = NetworkInterface.GetAllNetworkInterfaces();

            foreach (var network in networkInterfaces)
            {
                if (network.OperationalStatus != OperationalStatus.Up)
                {
                    continue;
                }

                var properties = network.GetIPProperties();

                if (properties.GatewayAddresses.Count == 0)
                {
                    continue;
                }

                foreach (var address in properties.UnicastAddresses)
                {
                    if (address.Address.AddressFamily != AddressFamily.InterNetwork)
                    {
                        continue;
                    }

                    if (IPAddress.IsLoopback(address.Address))
                    {
                        continue;
                    }

                    if (!address.IsDnsEligible)
                    {
                        if (mostSuitableIp == null)
                        {
                            mostSuitableIp = address;
                        }
                        continue;
                    }

                    // The best IP is the IP got from DHCP server
                    if (address.PrefixOrigin != PrefixOrigin.Dhcp)
                    {
                        if (mostSuitableIp == null || !mostSuitableIp.IsDnsEligible)
                        {
                            mostSuitableIp = address;
                        }
                        continue;
                    }

                    return(address.Address.ToString());
                }
            }

            return(mostSuitableIp != null
                ? mostSuitableIp.Address.ToString()
                : "");
        }
Ejemplo n.º 21
0
        private static IPAddress BroadcastAddress(UnicastIPAddressInformation poUAddress)
        {
            int lnIpAddress = BitConverter.ToInt32(poUAddress.Address.GetAddressBytes(), 0);
            int lnSubnet    = BitConverter.ToInt32(poUAddress.IPv4Mask.GetAddressBytes(), 0);
            int lnBroadcast = lnIpAddress | ~lnSubnet;

            return(new IPAddress(BitConverter.GetBytes(lnBroadcast)));
        }
Ejemplo n.º 22
0
 static public IPAddress GetIPv6LocalBroadcastAddress(UnicastIPAddressInformation address)
 {
     if (address.Address.AddressFamily != AddressFamily.InterNetworkV6 && !address.Address.IsIPv6LinkLocal)
     {
         throw new ArgumentException("Address is not an IPv6 Link Local address");
     }
     throw new NotImplementedException("Not yet implemented");
 }
Ejemplo n.º 23
0
 private static bool IsManuallyConfigured(UnicastIPAddressInformation unicastAddress)
 {
     // Only report IPv4 addresses with manual origin settings.
     return(unicastAddress.Address.AddressFamily ==
            System.Net.Sockets.AddressFamily.InterNetwork &&
            (unicastAddress.PrefixOrigin == PrefixOrigin.Manual) &&
            (unicastAddress.SuffixOrigin == SuffixOrigin.Manual));
 }
Ejemplo n.º 24
0
        private static string GetBroadcastAddress(UnicastIPAddressInformation unicastAddress)
        {
            uint ipAddress          = BitConverter.ToUInt32(unicastAddress.Address.GetAddressBytes(), 0);
            uint ipMaskV4           = BitConverter.ToUInt32(unicastAddress.IPv4Mask.GetAddressBytes(), 0);
            uint broadCastIpAddress = ipAddress | ~ipMaskV4;

            return(new IPAddress(BitConverter.GetBytes(broadCastIpAddress)).ToString());
        }
Ejemplo n.º 25
0
        public static IPAddress GetLocalIP()
        {
            IPAddress address;
            UnicastIPAddressInformation unicastIPAddressInformation = null;

            NetworkInterface[] allNetworkInterfaces = NetworkInterface.GetAllNetworkInterfaces();
            for (int i = 0; i < (int)allNetworkInterfaces.Length; i++)
            {
                NetworkInterface networkInterface = allNetworkInterfaces[i];
                if (networkInterface.OperationalStatus == OperationalStatus.Up)
                {
                    IPInterfaceProperties pProperties = networkInterface.GetIPProperties();
                    if (pProperties.GatewayAddresses.Count != 0 && !pProperties.GatewayAddresses[0].Address.Equals(IPAddress.Parse("0.0.0.0")))
                    {
                        using (IEnumerator <UnicastIPAddressInformation> enumerator = pProperties.UnicastAddresses.GetEnumerator())
                        {
                            while (enumerator.MoveNext())
                            {
                                UnicastIPAddressInformation current = enumerator.Current;
                                if (current.Address.AddressFamily != AddressFamily.InterNetwork || IPAddress.IsLoopback(current.Address))
                                {
                                    continue;
                                }
                                if (!current.IsDnsEligible)
                                {
                                    if (unicastIPAddressInformation != null)
                                    {
                                        continue;
                                    }
                                    unicastIPAddressInformation = current;
                                }
                                else if (current.PrefixOrigin == PrefixOrigin.Dhcp)
                                {
                                    address = current.Address;
                                    return(address);
                                }
                                else
                                {
                                    if (unicastIPAddressInformation != null && unicastIPAddressInformation.IsDnsEligible)
                                    {
                                        continue;
                                    }
                                    unicastIPAddressInformation = current;
                                }
                            }
                            goto Label0;
                        }
                        return(address);
                    }
                }
Label0:
            }
            if (unicastIPAddressInformation == null)
            {
                return(null);
            }
            return(unicastIPAddressInformation.Address);
        }
        public static uint GetPrefixLength(this UnicastIPAddressInformation addr)
        {
#if NET40
            return((uint)addr.GetPrivateProperty <int>("PrefixLength"));
#else
            var adapterAddress = addr.GetPrivateField <object>("adapterAddress");
            return(adapterAddress.GetPrivateField <uint>("length"));
#endif
        }
Ejemplo n.º 27
0
        // 現在のネットワーク状況に依存する情報の更新
        public void UpdateNetworkInformation(IPAddress ipaddress)
        {
            // 全てのネットワークインタフェースの情報を取得し、
            // 引数で指定されたIPアドレスを持つインタフェースの情報を採用する
            IPInterfaceProperties       ipproperties = null;
            UnicastIPAddressInformation information  = null;

            // 全てのネットワークインタフェース
            NetworkInterface[] interfaces = NetworkInterface.GetAllNetworkInterfaces();
            foreach (NetworkInterface ni in interfaces)
            {
                // ネットワーク接続している場合
                if (
                    (ni.OperationalStatus == OperationalStatus.Up) &&
                    (ni.NetworkInterfaceType != NetworkInterfaceType.Loopback) &&
                    (ni.NetworkInterfaceType != NetworkInterfaceType.Tunnel)
                    )
                {
                    IPInterfaceProperties ipip = ni.GetIPProperties();
                    if (ipip != null)
                    {
                        foreach (UnicastIPAddressInformation inf in ipip.UnicastAddresses)
                        {
                            if (inf.Address.Equals(ipaddress))
                            {
                                ipproperties = ipip;
                                information  = inf;
                            }
                        }
                    }
                }
            }

            // 情報取得
            if ((ipproperties != null) && (information != null))
            {
                // 自身のIPアドレス
                DhcpLeases.SERVER_IDENTIFIER_ = ipaddress;

                // サブネットマスク
                DhcpLeases.SUBNET_MASK_ = information.IPv4Mask;

                // GW
                DhcpLeases.ROUTER_ = new IPAddress(0);
                if (ipproperties.GatewayAddresses != null)
                {
                    DhcpLeases.ROUTER_ = ipproperties.GatewayAddresses[0].Address;
                }

                // DNS
                DhcpLeases.DOMAIN_NAME_SERVER_ = DhcpLeases.ROUTER_; // 取得できない場合はGWと同じとする
                if (ipproperties.DnsAddresses != null)
                {
                    DhcpLeases.DOMAIN_NAME_SERVER_ = ipproperties.DnsAddresses[0];
                }
            }
        }
Ejemplo n.º 28
0
        /// <summary>
        /// UnicastIPAddressInformation.IPv4Mask is not implemented in Xamarin. This method sits in a partial class definition
        /// on each native platform and retrieves the netmask in whatever way it can be done for each platform.
        /// </summary>
        /// <param name="ip"></param>
        /// <returns></returns>
        protected static IPAddress GetSubnetMask(UnicastIPAddressInformation ip)
        {
            // use native calls to get comprehensive interface info
            var nativeInterfaceInfo = NetInfo.GetInterfaceInfo();

            // match or nothing
            var match = nativeInterfaceInfo.FirstOrDefault(ni => ni != null && ni.Address != null && ip != null && ip.Address != null && Equals(ni.Address, ip.Address));

            return(match != null ? match.Netmask : null);
        }
        /// <summary>
        /// Initializes new instance of <see cref="UnicastIPAddressInformationAdapter"/>.
        /// </summary>
        /// <param name="info">Information to be used by the adapter.</param>
        public UnicastIPAddressInformationAdapter(UnicastIPAddressInformation info)
            : base(info)
        {
            if (info == null)
            {
                throw new ArgumentNullException(nameof(info));
            }

            _info = info;
        }
Ejemplo n.º 30
0
        private Profile MatchNetwork(UnicastIPAddressInformation ipAddr, GatewayIPAddressInformation gw, byte[] addrBytes, byte[] maskBytes)
        {
            var     maxConfidence = 0;
            Profile result        = null;

            foreach (var item in _profiles)
            {
                var confidence = 6;

                if (item.Subnet.Value == null)
                {
                    confidence -= 1;
                }
                else if (!item.Subnet.Value.Equals(ipAddr.IPv4Mask))
                {
                    confidence = 0;
                }

                if (item.IPAddress.Value == null)
                {
                    confidence -= 1;
                }
                else
                {
                    var compBytes = item.IPAddress.Value.GetAddressBytes();
                    for (var i = 0; i < compBytes.Length; i++)
                    {
                        if ((addrBytes[i] & maskBytes[i]) !=
                            (compBytes[i] & maskBytes[i]))
                        {
                            confidence = 0;
                            break;
                        }
                    }
                }

                if (item.Gateway.Value == null)
                {
                    confidence -= 1;
                }
                else if (!item.Gateway.Value.Equals(gw.Address))
                {
                    confidence = 0;
                }

                confidence = Math.Max(0, confidence);
                if (confidence > maxConfidence)
                {
                    maxConfidence = confidence;
                    result        = item;
                }
            }

            return(result);
        }
Ejemplo n.º 31
0
    private static IPAddress CalculateNetwork(UnicastIPAddressInformation addr)
    {
        // The mask will be null in some scenarios, like a dhcp address 169.254.x.x
        if (addr.IPv4Mask == null)
        return null;

        var ip = addr.Address.GetAddressBytes();
        var mask = addr.IPv4Mask.GetAddressBytes();
        var result = new Byte[4];
        for (int i = 0; i < 4; ++i)
        {
        result[i] = (Byte)(ip[i] & mask[i]);
        }

        return new IPAddress(result);
    }