예제 #1
0
        public override bool Equals(object obj)
        {
            if (obj is IPAddressItem other)
            {
                return
                    (IPAddress?.Equals(other.IPAddress) == true &&
                     InterfaceId?.Equals(other.InterfaceId) == true);
            }

            return(base.Equals(obj));
        }
        private void Receive()
        {
            try
            {
                byte[]   _receiveBuffer = new byte[_socket.Available];               // Read everything, that is available at once!
                EndPoint ipEndPoint     = new IPEndPoint(IPAddress.Any, Port);
                _socket.ReceiveFrom(_receiveBuffer, 0, _receiveBuffer.Length, SocketFlags.None, ref ipEndPoint);

                if (ListenToAllAdresses == false)
                {
                    IPAddress connectedAddress = ((IPEndPoint)ipEndPoint).Address;

                    if (_remoteIp == null)                     // Only happens the first time or if _listenToAllAdresses was set to false during runtime.
                    {
                        _remoteIp = IPAddress.Parse(_remoteIpAddress);
                    }

                    if (connectedAddress.Equals(_remoteIp) == false)
                    {
                        Debug.LogWarning("Got network package from unaccepted endpoint (" + connectedAddress.ToString() + "). Expected endpoint is " + _remoteIpAddress + "."
                                         + "\nPackage is not going to be read!");
                        return;
                    }
                }

                if (_receiveBuffer != null && _receiveBuffer.Length > 0)                 // If we received some bytes:
                {
                    // Call each subscriber that bytes have been received:
                    foreach (ReceivedMessageDelegate ReceiveCallack in OnReceivedMessage.GetInvocationList())
                    {
                        try
                        {
                            ReceiveCallack(_receiveBuffer, ((IPEndPoint)ipEndPoint).Address);
                        }
                        catch (System.Exception ex)
                        {
                            Debug.LogException(ex);
                        }
                    }
                }
            }
            catch (Exception receiveException)
            {
                Debug.LogException(receiveException);
            }
        }
예제 #3
0
    IPAddress FindBroadcastAdress()
    {
        IPAddress broadcast = null;

        IPAddress[] localIPs = Dns.GetHostAddresses(Dns.GetHostName());

        bool success = false;

        for (int i = localIPs.Length - 1; i > -1; --i)
        {
            var localIP = localIPs[i];

            foreach (var netInterface in NetworkInterface.GetAllNetworkInterfaces())
            {
                if (netInterface.NetworkInterfaceType == NetworkInterfaceType.Wireless80211 ||
                    netInterface.NetworkInterfaceType == NetworkInterfaceType.Ethernet)
                {
                    foreach (var address in netInterface.GetIPProperties().UnicastAddresses)
                    {
                        IPAddress hostIP = address.Address;
                        if (hostIP.Equals(localIP))
                        {
                            var addressInt = BitConverter.ToInt32(address.Address.GetAddressBytes(), 0);

                            var maskInt      = BitConverter.ToInt32(address.IPv4Mask.GetAddressBytes(), 0);
                            var broadcastInt = addressInt | ~maskInt;
                            broadcast = new IPAddress(BitConverter.GetBytes(broadcastInt));
                            endPoint  = new IPEndPoint(broadcast, BROADCAST_PORT);
                            success   = true;
                            BroadcastIP("HI");
                            //Debug.Log($"Broadcasted - {broadcast}");
                        }
                    }
                }
            }
        }


        if (broadcast == null || !success)
        {
            enabled = false;
            throw new ApplicationException("Broadcast IP NOT FOUND.");
        }

        return(broadcast);
    }
예제 #4
0
        public DotcoinNetwork(IPAddress nodeIp, IPAddress masterIp, IDotcoinServer dotcoinDotcoinServer, string knownIpFile = "")
        {
            _nodeIp        = nodeIp;
            _masterIp      = masterIp;
            _dotcoinServer = dotcoinDotcoinServer;

            _addresses.TryAdd(nodeIp, DateTime.Now);

            if (!nodeIp.Equals(masterIp)) //helps prevent glitch when working locally
            {
                _addresses.TryAdd(masterIp, DateTime.Now);
            }

            LoadKnownIps(knownIpFile);

            _dotcoinServer.StartServer(_nodeIp, PORT);
        }
예제 #5
0
        void ParseRouteInfo(string iface)
        {
            try
            {
                gateways = new IPAddressCollection();
                using (StreamReader reader = new StreamReader("/proc/net/route"))
                {
                    string line;
                    reader.ReadLine(); // Ignore first line
                    while ((line = reader.ReadLine()) != null)
                    {
                        line = line.Trim();
                        if (line.Length == 0)
                        {
                            continue;
                        }

                        string [] parts = line.Split('\t');
                        if (parts.Length < 3)
                        {
                            continue;
                        }
                        string  gw_address = parts [2].Trim();
                        byte [] ipbytes    = new byte [4];
                        if (gw_address.Length == 8 && iface.Equals(parts [0], StringComparison.OrdinalIgnoreCase))
                        {
                            for (int i = 0; i < 4; i++)
                            {
                                if (!Byte.TryParse(gw_address.Substring(i * 2, 2), NumberStyles.HexNumber, null, out ipbytes [3 - i]))
                                {
                                    continue;
                                }
                            }
                            IPAddress ip = new IPAddress(ipbytes);
                            if (!ip.Equals(IPAddress.Any))
                            {
                                gateways.Add(ip);
                            }
                        }
                    }
                }
            }
            catch
            {
            }
        }
예제 #6
0
        private void TimerMethod()
        {
            try
            {
                IPAddress   ipAddress    = GetIpAddress();
                SystemState state        = SystemState.Load(m_Settings.GetValue("StateDir"));
                IPAddress   oldIpAddress = state.LastAddress;

                if (!ipAddress.Equals(oldIpAddress))
                {
                    Log.WriteLine("Address has changed from " + oldIpAddress + " to " + ipAddress);

                    string result = "";

                    string value = m_Settings.GetValue("Dns Domains");
                    foreach (string domain in value.Split(','))
                    {
                        try
                        {
                            result = UpdateDns(ipAddress, domain, m_Settings.GetValue("Dns Username"), m_Settings.GetValue("Dns Password"));
                            Log.WriteLine(result);
                        }
                        catch (Exception e)
                        {
                            Log.Write(e);
                            result += "\n\n" + e.ToString();
                        }
                    }

                    state.LastAddress = ipAddress;

                    try
                    {
                        Notify(ipAddress.ToString(), result);
                    }
                    catch (Exception e)
                    {
                        Log.Write(e);
                    }
                }
            }
            catch (Exception e)
            {
                Log.Write(e);
            }
        }
예제 #7
0
파일: ip.cs 프로젝트: orf53975/C--IPV4Tools
 public static IPAddress getSubnetmask(IPAddress ip)
 {
     foreach (NetworkInterface face in NetworkInterface.GetAllNetworkInterfaces())
     {
         foreach (UnicastIPAddressInformation unicastinfo in face.GetIPProperties().UnicastAddresses)
         {
             if (unicastinfo.Address.AddressFamily == AddressFamily.InterNetwork)
             {
                 if (ip.Equals(unicastinfo.Address))
                 {
                     return(unicastinfo.IPv4Mask);
                 }
             }
         }
     }
     throw new ArgumentException("No Subnetmask Found!");
 }
예제 #8
0
 public static string DeviceDescription(IPAddress address)
 {
     foreach (NetworkInterface adapter in NetworkInterface.GetAllNetworkInterfaces())
     {
         foreach (UnicastIPAddressInformation unicastIPAddressInformation in adapter.GetIPProperties().UnicastAddresses)
         {
             if (unicastIPAddressInformation.Address.AddressFamily == AddressFamily.InterNetwork)
             {
                 if (address.Equals(unicastIPAddressInformation.Address))
                 {
                     return(adapter.Description);
                 }
             }
         }
     }
     return(null);
 }
예제 #9
0
 /// <summary>
 /// Check if two ip are equal, using MapToIPv6 if needed
 /// </summary>
 /// <param name="ipAddress">IP address</param>
 /// <param name="other">Other ip address</param>
 /// <returns>True if ip are equal or equal, false otherwise</returns>
 public static bool EqualsWithMapToIPv6(this System.Net.IPAddress ipAddress, System.Net.IPAddress other)
 {
     if (ipAddress.Equals(other))
     {
         return(true);
     }
     try
     {
         IPAddress ipv6      = (ipAddress.IsLocalHost() ? IPAddress.Parse("::1") : ipAddress.MapToIPv6());
         IPAddress otherIPV6 = (other.IsLocalHost() ? IPAddress.Parse("::1") : other.MapToIPv6());
         return(ipv6.Equals(otherIPV6));
     }
     catch
     {
         return(false);
     }
 }
예제 #10
0
 public static IPAddress GetSubnetMask(this IPAddress address)
 {
     foreach (var adapter in NetworkInterface.GetAllNetworkInterfaces())
     {
         foreach (var unicastIP in adapter.GetIPProperties().UnicastAddresses)
         {
             if (unicastIP.Address.AddressFamily == AddressFamily.InterNetwork)
             {
                 if (address.Equals(unicastIP.Address))
                 {
                     return(unicastIP.IPv4Mask);
                 }
             }
         }
     }
     return(null);
 }
예제 #11
0
 private IPAddress getSubnetMask(IPAddress address)
 {
     foreach (NetworkInterface adapter in NetworkInterface.GetAllNetworkInterfaces())
     {
         foreach (UnicastIPAddressInformation unicastIPAddressInformation in adapter.GetIPProperties().UnicastAddresses)
         {
             if (unicastIPAddressInformation.Address.AddressFamily == AddressFamily.InterNetwork)
             {
                 if (address.Equals(unicastIPAddressInformation.Address))
                 {
                     return(unicastIPAddressInformation.IPv4Mask);
                 }
             }
         }
     }
     throw new ArgumentException(string.Format("Не получилось найти маску подсети для адреса: '{0}'", address));
 }
예제 #12
0
        /// <summary>
        ///     Determines whether the specified <see cref="System.Net.IPAddress" /> represents
        ///     the local IP address.
        /// </summary>
        /// <returns>
        ///     <c>true</c> if <paramref name="address" /> represents the local IP address;
        ///     otherwise, <c>false</c>.
        /// </returns>
        /// <param name="address">
        ///     A <see cref="System.Net.IPAddress" /> to test.
        /// </param>
        /// <exception cref="ArgumentNullException">
        ///     <paramref name="address" /> is <see langword="null" />.
        /// </exception>
        public static bool IsLocal(this IPAddress address)
        {
            if (address == null)
            {
                throw new ArgumentNullException(nameof(address));
            }

            if (address.Equals(IPAddress.Any) || IPAddress.IsLoopback(address))
            {
                return(true);
            }

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

            return(addrs.Contains(address));
        }
예제 #13
0
 public static IPAddress GetSubnetMask(IPAddress address)
 {
     foreach (NetworkInterface adapter in NetworkInterface.GetAllNetworkInterfaces())
     {
         foreach (UnicastIPAddressInformation unicastIPAddressInformation in adapter.GetIPProperties().UnicastAddresses)
         {
             if (unicastIPAddressInformation.Address.AddressFamily == AddressFamily.InterNetwork)
             {
                 if (address.Equals(unicastIPAddressInformation.Address))
                 {
                     return(unicastIPAddressInformation.IPv4Mask);
                 }
             }
         }
     }
     throw new ArgumentException(string.Format("Can't find subnetmask for IP address '{0}'", address));
 }
예제 #14
0
 public static IPAddress GetSubnetMask(IPAddress address)
 {
     foreach (NetworkInterface adapter in NetworkInterface.GetAllNetworkInterfaces())
     {
         foreach (UnicastIPAddressInformation unicastIPAddressInformation in adapter.GetIPProperties().UnicastAddresses)
         {
             if (unicastIPAddressInformation.Address.AddressFamily == AddressFamily.InterNetwork)
             {
                 if (address.Equals(unicastIPAddressInformation.Address))
                 {
                     return(unicastIPAddressInformation.IPv4Mask);
                 }
             }
         }
     }
     return(IPAddress.None);
 }
예제 #15
0
 void HandleStatsChanged(object sender, EventArgs e)
 {
     ThreadAssist.ProxyToMain(() => {
         if (last_ip == null || !last_ip.Equals(stats.LastIP))
         {
             last_ip = stats.LastIP;
             try {
                 last_client = Dns.GetHostEntry(last_ip).HostName;
             }
             catch (Exception) {
                 last_client = last_ip != null ? last_ip.ToString() : Catalog.GetString("none");
             }
         }
         stats_label.Text = string.Format(Catalog.GetString(" Gallery: {0},  Photos: {1},  Last client: {3}"),
                                          stats.GalleryViews, stats.PhotoViews, stats.BytesSent / 1024, last_client);
     });
 }
예제 #16
0
        public void DNSTest()
        {
            INetworkInterface[] interfaces = NetworkInterface.GetAllNetworkInterfaces();

            Assert.IsTrue(interfaces.Length > 0, "No interfaces available to test");

            // make sure DHCP is not enabled
            bool wasDhcpEnabled = interfaces[0].GetIPProperties().GetIPv4Properties().IsDhcpEnabled;

            if (wasDhcpEnabled)
            {
                interfaces[0].GetIPProperties().GetIPv4Properties().IsDhcpEnabled = false;
                interfaces[0].Rebind();
            }

            if (interfaces[0].GetIPProperties().DnsAddresses.Count == 0)
            {
                interfaces[0].GetIPProperties().DnsAddresses.Add(IPAddress.Parse("30.30.30.3"));
                interfaces[0].Rebind();
                Assert.AreEqual <int>(1, interfaces[0].GetIPProperties().DnsAddresses.Count, "Add did not increment DNS count");
            }

            IPAddress oldDns = interfaces[0].GetIPProperties().DnsAddresses[0];
            IPAddress newDns = IPAddress.Parse("30.30.30.4");

            if (oldDns.Equals(newDns))
            {
                newDns = IPAddress.Parse("30.30.30.5");
            }

            interfaces[0].GetIPProperties().DnsAddresses[0] = newDns;
            interfaces[0].Rebind();

            IPAddress setDns = interfaces[0].GetIPProperties().DnsAddresses[0];

            Assert.IsTrue(setDns.Equals(newDns), string.Format("DNS read back ({0}) did not match what we wrote in ({1})", setDns.Address, newDns.Address));

            // restore
            if (wasDhcpEnabled)
            {
                interfaces[0].GetIPProperties().GetIPv4Properties().IsDhcpEnabled = true;
            }
            interfaces[0].GetIPProperties().DnsAddresses[0] = oldDns;
            interfaces[0].Rebind();
        }
 private void ParseRouteInfo(string iface)
 {
     try
     {
         this.gateways = new IPAddressCollection();
         using (StreamReader streamReader = new StreamReader("/proc/net/route"))
         {
             streamReader.ReadLine();
             string text;
             while ((text = streamReader.ReadLine()) != null)
             {
                 text = text.Trim();
                 if (text.Length != 0)
                 {
                     string[] array = text.Split(new char[]
                     {
                         '\t'
                     });
                     if (array.Length >= 3)
                     {
                         string text2  = array[2].Trim();
                         byte[] array2 = new byte[4];
                         if (text2.Length == 8 && iface.Equals(array[0], StringComparison.OrdinalIgnoreCase))
                         {
                             for (int i = 0; i < 4; i++)
                             {
                                 if (!byte.TryParse(text2.Substring(i * 2, 2), NumberStyles.HexNumber, null, out array2[3 - i]))
                                 {
                                 }
                             }
                             IPAddress ipaddress = new IPAddress(array2);
                             if (!ipaddress.Equals(IPAddress.Any))
                             {
                                 this.gateways.Add(ipaddress);
                             }
                         }
                     }
                 }
             }
         }
     }
     catch
     {
     }
 }
예제 #18
0
        public bool StartListen(IPAddress localAddr, int port)
        {
            StopListen();

            bool bValidAddr = false;

            IPAddress[] addrList = Dns.GetHostEntry(Dns.GetHostName()).AddressList;
            for (int i = 0; i < addrList.Length; i++)
            {
                if (localAddr.Equals(addrList[i]))
                {
                    bValidAddr = true;
                    break;
                }
            }

            if (!bValidAddr)
            {
                return(false);
            }

            listen = new TcpListener(localAddr, port);

            lock (strListeningLocalEndPoint)
            {
                strListeningLocalEndPoint = listen.LocalEndpoint.ToString();
            }

            threadListen = new Thread(new ThreadStart(Listen));

            try
            {
                listen.Start();
                threadListen.Start();
            }
            catch (System.Exception ex)
            {
                System.Diagnostics.Trace.Write(ex.Message + "\n");

                StopListen();

                return(false);
            }
            return(true);
        }
예제 #19
0
        // TODO: Write unit tests.
        /// <summary>
        /// Checks if an <paramref name="ip"/> is allowed according to a whitelist of <paramref name="allowed"/>
        /// IPs. Supports individual IPv4, individual IPv6, masked IPv4 range, dynamic DNS.
        /// </summary>
        public static async Task <bool> CheckIpValidity(IPAddress ip, IEnumerable <string> allowed)
        {
            foreach (var addr in allowed)
            {
                try
                {
                    // Check if standard IPv4 or IPv6
                    if (Regex.Match(addr, @"^((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)(\.|$)){4}$").Success ||
                        Regex.Match(addr, @"^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$").Success)
                    {
                        if (ip.Equals(IPAddress.Parse(addr)))
                        {
                            return(true);
                        }
                    }

                    // Check if masked IPv4
                    if (addr.Contains('/'))
                    {
                        var split      = addr.Split('/');
                        var maskLength = int.Parse(split[1]);
                        var toCompare  = IPAddress.Parse(split[0]);
                        var mask       = SubnetMask.CreateByNetBitLength(maskLength);

                        if (ip.IsInSameSubnet(toCompare, mask))
                        {
                            return(true);
                        }
                    }

                    // Otherwise it must be a dynamic DNS
                    var resolved = await Dns.GetHostEntryAsync(addr);

                    if (resolved.AddressList.Any(a => a.Equals(ip)))
                    {
                        return(true);
                    }
                }
                catch
                {
                }
            }

            return(false);
        }
 public static bool IsAddressOnInterface(IPAddress address)
 {
     foreach (NetworkInterface ni in NetworkInterface.GetAllNetworkInterfaces())
     {
         if (ni.NetworkInterfaceType != NetworkInterfaceType.Loopback)
         {
             foreach (UnicastIPAddressInformation ip in ni.GetIPProperties().UnicastAddresses)
             {
                 if (ip.Address.AddressFamily == AddressFamily.InterNetwork &&
                     address.Equals(ip.Address) && !IPAddress.IsLoopback(ip.Address))
                 {
                     return(true);
                 }
             }
         }
     }
     return(IPAddress.IsLoopback(address));
 }
예제 #21
0
        private void Button1_Click(object sender, EventArgs e)
        {
            // 將IP位址字串轉換為IPAddress類別
            IPAddress ipAddr1 = IPAddress.Parse(txtIP1.Text);
            IPAddress ipAddr2 = IPAddress.Parse(txtIP2.Text);

            // 比較兩IP位址是否相同
            if (ipAddr1.Equals(ipAddr2))
            {
                // 兩IP位址相同
                MessageBox.Show(ipAddr1.ToString() + " is equal to " + ipAddr2.ToString(), "IP Address", MessageBoxButtons.OK, MessageBoxIcon.Information, MessageBoxDefaultButton.Button1);
            }
            else
            {
                // 兩IP位址不相同
                MessageBox.Show(ipAddr1.ToString() + " is different from " + ipAddr2.ToString(), "IP Address", MessageBoxButtons.OK, MessageBoxIcon.Information, MessageBoxDefaultButton.Button1);
            }
        }
예제 #22
0
 public static IPAddress GetSubnetMaskFromIPv4(IPAddress adapterAddress)
 {
     foreach (NetworkInterface adapter in NetworkInterface.GetAllNetworkInterfaces())
     {
         foreach (UnicastIPAddressInformation unicastIPAddressInfo in adapter.GetIPProperties().UnicastAddresses)
         {
             if (unicastIPAddressInfo.Address.AddressFamily == AddressFamily.InterNetwork)
             {
                 if (adapterAddress.Equals(unicastIPAddressInfo.Address))
                 {
                     return(unicastIPAddressInfo.IPv4Mask);
                 }
             }
         }
     }
     Debug.LogErrorFormat("Can't find subnetmask for IP address '{0}'", adapterAddress);
     return(new IPAddress(0));
 }
예제 #23
0
 /// <summary>
 /// Returns the IPv4 subnet mask of the network interface with the given IPv4 address.
 /// </summary>
 public static IPAddress GetSubnetMask(IPAddress address)
 {
     foreach (NetworkInterface adapter in NetworkInterface.GetAllNetworkInterfaces())
     {
         foreach (UnicastIPAddressInformation unicastIPAddressInformation in adapter.GetIPProperties().UnicastAddresses)
         {
             var unicastAddress = unicastIPAddressInformation.Address;
             if (unicastAddress.AddressFamily == AddressFamily.InterNetwork)
             {
                 if (address.Equals(unicastAddress))
                 {
                     return(unicastIPAddressInformation.IPv4Mask);
                 }
             }
         }
     }
     throw new ArgumentException("Network interface with IPv4 address " + address + " does not exist.");
 }
예제 #24
0
        /// <summary>
        /// Determines whether the two IP address lists are equal.
        /// </summary>
        /// <param name="addressList1">The first IP address list.</param>
        /// <param name="addressList2">The second IP address list.</param>
        /// <returns></returns>
        private static bool AddressListEquals(IPAddress[] addressList1, IPAddress[] addressList2)
        {
            Contract.Assert(addressList1 != null);
            Contract.Assert(addressList2 != null);

            for (int i = 0; i < addressList1.Length; i++)
            {
                for (int j = 0; j < addressList2.Length; j++)
                {
                    if (IPAddress.Equals(addressList1[i], addressList2[j]))
                    {
                        return(true);
                    }
                }
            }

            return(false);
        }
예제 #25
0
 public static IEnumerable <Player> NotFromIP([NotNull] this IEnumerable <Player> source, [NotNull] IPAddress ip)
 {
     if (source == null)
     {
         throw new ArgumentNullException("source");
     }
     if (ip == null)
     {
         throw new ArgumentNullException("ip");
     }
     foreach (Player player in source)
     {
         if (!ip.Equals(player.IP))
         {
             yield return(player);
         }
     }
 }
예제 #26
0
        static bool IsMatchingRow(IPAddress remoteAddress, MIB_IPNET_ROW2 row)
        {
            byte[] addressBytes;
            switch (row.Address.si_family)
            {
            case AF_INET:
                addressBytes = row.Address.Ipv4.Address;
                break;

            case AF_INET6:
                addressBytes = row.Address.Ipv6.Address;
                break;

            default:
                return(false);
            }
            return(remoteAddress.Equals(new IPAddress(addressBytes)));
        }
예제 #27
0
 public static IPAddress GetSubnetMask(IPAddress address)
 {
     foreach (NetworkInterface adapter in NetworkInterface.GetAllNetworkInterfaces())
     {
         foreach (UnicastIPAddressInformation unicastIPAddressInformation in adapter.GetIPProperties().UnicastAddresses)
         {
             if (unicastIPAddressInformation.Address.AddressFamily == AddressFamily.InterNetwork)
             {
                 if (address.Equals(unicastIPAddressInformation.Address))
                 {
                     // the following mask can be null.. return 255.255.255.0 in that case
                     return(unicastIPAddressInformation.IPv4Mask ?? new IPAddress(new byte[] { 255, 255, 255, 0 }));
                 }
             }
         }
     }
     throw new ArgumentException(string.Format("Can't find subnetmask for IP address '{0}'", address));
 }
예제 #28
0
 public static IPAddress GetSubnetMask(IPAddress ipAddress)
 {
     foreach (NetworkInterface netInterface in NetworkInterface.GetAllNetworkInterfaces())
     {
         IPInterfaceProperties ipProperties = netInterface.GetIPProperties();
         foreach (UnicastIPAddressInformation addressInfo in ipProperties.UnicastAddresses)
         {
             if (addressInfo.Address.AddressFamily == AddressFamily.InterNetwork)
             {
                 if (IPAddress.Equals(addressInfo.Address, ipAddress))
                 {
                     return(addressInfo.IPv4Mask);
                 }
             }
         }
     }
     return(null);
 }
예제 #29
0
        public static bool IsBlocked(IPAddress ip)
        {
            bool contains = false;

            for (int i = 0; !contains && i < m_Blocked.Count; ++i)
            {
                if (m_Blocked[i] is IPAddress)
                {
                    contains = ip.Equals(m_Blocked[i]);
                }
                else if (m_Blocked[i] is String)
                {
                    contains = Utility.IPMatch((string)m_Blocked[i], ip);
                }
            }

            return(contains);
        }
예제 #30
0
        /// <summary>
        /// Checks whether the given IP address requires the encryption.
        /// </summary>
        /// <param name="clientAddress">The client address.</param>
        private bool RequireEncryption(IPAddress clientAddress)
        {
            if (clientAddress == null || _securityExemptionList == null || _securityExemptionList.Length == 0)
                return _requireCryptoClient;

            bool found = false;

            foreach (IPAddress address in _securityExemptionList)
            {
                if (clientAddress.Equals(address))
                {
                    found = true;
                    break;
                }
            }

            return found ? !_requireCryptoClient : _requireCryptoClient;
        }
예제 #31
0
파일: Ping.cs 프로젝트: ESgarbi/corefx
        public Task<PingReply> SendPingAsync(IPAddress address, int timeout, byte[] buffer, PingOptions options)
        {
            if (buffer == null)
            {
                throw new ArgumentNullException(nameof(buffer));
            }

            if (buffer.Length > MaxBufferSize)
            {
                throw new ArgumentException(SR.net_invalidPingBufferSize, nameof(buffer));
            }

            if (timeout < 0)
            {
                throw new ArgumentOutOfRangeException(nameof(timeout));
            }

            if (address == null)
            {
                throw new ArgumentNullException(nameof(address));
            }

            // Check if address family is installed.
            TestIsIpSupported(address);

            if (address.Equals(IPAddress.Any) || address.Equals(IPAddress.IPv6Any))
            {
                throw new ArgumentException(SR.net_invalid_ip_addr, nameof(address));
            }

            // Need to snapshot the address here, so we're sure that it's not changed between now
            // and the operation, and to be sure that IPAddress.ToString() is called and not some override.
            IPAddress addressSnapshot = (address.AddressFamily == AddressFamily.InterNetwork) ?
                new IPAddress(address.GetAddressBytes()) :
                new IPAddress(address.GetAddressBytes(), address.ScopeId);

            CheckStart();
            try
            {
                return SendPingAsyncCore(addressSnapshot, buffer, timeout, options);
            }
            catch (Exception e)
            {
                Finish();
                return Task.FromException<PingReply>(new PingException(SR.net_ping, e));
            }
        }
예제 #32
0
		IPAddressCollection ParseRouteInfo (string iface)
		{
			var col = new IPAddressCollection ();
			try {
				using (StreamReader reader = new StreamReader ("/proc/net/route")) {
					string line;
					reader.ReadLine (); // Ignore first line
					while ((line = reader.ReadLine ()) != null) {
						line = line.Trim ();
						if (line.Length == 0)
							continue;

						string [] parts = line.Split ('\t');
						if (parts.Length < 3)
							continue;
						string gw_address = parts [2].Trim ();
						byte [] ipbytes = new byte [4];
						if (gw_address.Length == 8 && iface.Equals (parts [0], StringComparison.OrdinalIgnoreCase)) {
							for (int i = 0; i < 4; i++) {
								if (!Byte.TryParse (gw_address.Substring (i * 2, 2), NumberStyles.HexNumber, null, out ipbytes [3 - i]))
									continue;
							}
							IPAddress ip = new IPAddress (ipbytes);
							if (!ip.Equals (IPAddress.Any) && !col.Contains (ip))
								col.InternalAdd (ip);
						}
					}
				}
			} catch {
			}

			return col;
		}
예제 #33
0
        public static void Equals_Compare_Success()
        {
            IPAddress ip1 = IPAddress.Parse("192.168.0.9"); //IpV4
            IPAddress ip2 = IPAddress.Parse("192.168.0.9"); //IpV4
            IPAddress ip3 = IPAddress.Parse("169.192.1.10"); //IpV4

            IPAddress ip4 = new IPAddress(ipV6AddressBytes1); //IpV6
            IPAddress ip5 = new IPAddress(ipV6AddressBytes1); //IpV6
            IPAddress ip6 = new IPAddress(ipV6AddressBytes2); //IpV6

            Assert.True(ip1.Equals(ip2));
            Assert.True(ip2.Equals(ip1));

            Assert.True(ip1.GetHashCode().Equals(ip2.GetHashCode()));
            Assert.False(ip1.GetHashCode().Equals(ip3.GetHashCode()));

            Assert.False(ip1.Equals(ip3));

            Assert.False(ip1.Equals(ip4)); //IpV4 /= IpV6
            Assert.False(ip1.Equals(null));
            Assert.False(ip1.Equals(""));

            Assert.True(ip4.Equals(ip5));
            Assert.False(ip4.Equals(ip6));

            Assert.True(ip4.GetHashCode().Equals(ip5.GetHashCode()));
            Assert.False(ip4.GetHashCode().Equals(ip6.GetHashCode()));
        }
예제 #34
0
 private bool IsBroadcast(IPAddress address)
 {
     if (address.AddressFamily == AddressFamily.InterNetworkV6)
     {
         // No such thing as a broadcast address for IPv6.
         return false;
     }
     else
     {
         return address.Equals(IPAddress.Broadcast);
     }
 }
예제 #35
0
        private void SendAsync(IPAddress address, int timeout, byte[] buffer, PingOptions options, object userToken)
        {
            if (buffer == null)
            {
                throw new ArgumentNullException("buffer");
            }

            if (buffer.Length > MaxBufferSize)
            {
                throw new ArgumentException(SR.net_invalidPingBufferSize, "buffer");
            }

            if (timeout < 0)
            {
                throw new ArgumentOutOfRangeException("timeout");
            }

            if (address == null)
            {
                throw new ArgumentNullException("address");
            }

            // Check if address family is installed.
            TestIsIpSupported(address);

            if (address.Equals(IPAddress.Any) || address.Equals(IPAddress.IPv6Any))
            {
                throw new ArgumentException(SR.net_invalid_ip_addr, "address");
            }

            // FxCop: need to snapshot the address here, so we're sure that it's not changed between the permission
            // check and the operation, and to be sure that IPAddress.ToString() is called and not some override.
            IPAddress addressSnapshot;
            if (address.AddressFamily == AddressFamily.InterNetwork)
            {
                addressSnapshot = new IPAddress(address.GetAddressBytes());
            }
            else
            {
                addressSnapshot = new IPAddress(address.GetAddressBytes(), address.ScopeId);
            }

            CheckStart(true);
            try
            {
                _cancelled = false;
                _asyncOp = AsyncOperationManager.CreateOperation(userToken);
                InternalSend(addressSnapshot, buffer, timeout, options, true);
            }
            catch (Exception e)
            {
                Finish(true);
                throw new PingException(SR.net_ping, e);
            }
        }