System.Net.IPAddress.GetAddressBytes()

Here are the examples of the csharp api System.Net.IPAddress.GetAddressBytes() taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

534 Examples 7

19 View Source File : IPAddressExtensions.cs
License : MIT License
Project Creator : araditc

static IPAddress And(this IPAddress address, IPAddress netmask) {
			netmask.ThrowIfNull("netmask");
			if (address.AddressFamily != netmask.AddressFamily)
				throw new ArgumentException("The address family of the specified netmask " +
					"is different from the address family of the IP address.");
			byte[] buffer = address.GetAddressBytes();
			byte[] other = netmask.GetAddressBytes();
			for (int i = 0; i < buffer.Length; i++)
				buffer[i] = (byte) (buffer[i] & other[i]);
			return new IPAddress(buffer);
		}

19 View Source File : CrawlerHandler.cs
License : MIT License
Project Creator : baiyunchen

private bool IsExternalIpAddress(string url)
        {
            var uri = new Uri(url);
            switch (uri.HostNameType)
            {
                case UriHostNameType.Dns:
                    var ipHostEntry = Dns.GetHostEntry(uri.DnsSafeHost);
                    foreach (IPAddress ipAddress in ipHostEntry.AddressList)
                    {
                        byte[] ipBytes = ipAddress.GetAddressBytes();
                        if (ipAddress.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)
                        {
                            if (!IsPrivateIP(ipAddress))
                            {
                                return true;
                            }
                        }
                    }
                    break;

                case UriHostNameType.IPv4:
                    return !IsPrivateIP(IPAddress.Parse(uri.DnsSafeHost));
            }
            return false;
        }

19 View Source File : IPAddressExtension.cs
License : Apache License 2.0
Project Creator : alexreinert

public static string GetReverseLookupAddress(this IPAddress ipAddress)
		{
			if (ipAddress == null)
				throw new ArgumentNullException("ipAddress");

			StringBuilder res = new StringBuilder();

			byte[] addressBytes = ipAddress.GetAddressBytes();

			if (ipAddress.AddressFamily == AddressFamily.InterNetwork)
			{
				for (int i = addressBytes.Length - 1; i >= 0; i--)
				{
					res.Append(addressBytes[i]);
					res.Append(".");
				}
				res.Append("in-addr.arpa");
			}
			else
			{
				for (int i = addressBytes.Length - 1; i >= 0; i--)
				{
					string hex = addressBytes[i].ToString("x2");
					res.Append(hex[1]);
					res.Append(".");
					res.Append(hex[0]);
					res.Append(".");
				}

				res.Append("ip6.arpa");
			}

			return res.ToString();
		}

19 View Source File : Utils.cs
License : MIT License
Project Creator : AmazingDM

public static bool SearchOutboundAdapter(bool logging = true)
        {
            // 寻找出口适配器
            if (Win32Native.GetBestRoute(BitConverter.ToUInt32(IPAddress.Parse("114.114.114.114").GetAddressBytes(), 0),
                0, out var pRoute) != 0)
            {
                Logging.Error("GetBestRoute 搜索失败");
                return false;
            }

            Global.Outbound.Index = pRoute.dwForwardIfIndex;
            // 根据 IP Index 寻找 出口适配器
            try
            {
                var adapter = NetworkInterface.GetAllNetworkInterfaces().First(_ =>
                {
                    try
                    {
                        return _.GetIPProperties().GetIPv4Properties().Index == Global.Outbound.Index;
                    }
                    catch
                    {
                        return false;
                    }
                });
                Global.Outbound.Adapter = adapter;
                Global.Outbound.Gateway = new IPAddress(pRoute.dwForwardNextHop);
                if (logging)
                {
                    Logging.Info($"出口 IPv4 地址:{Global.Outbound.Address}");
                    Logging.Info($"出口 网关 地址:{Global.Outbound.Gateway}");
                    Logging.Info($"出口适配器:{adapter.Name} {adapter.Id} {adapter.Description}, index: {Global.Outbound.Index}");
                }

                return true;
            }
            catch (Exception e)
            {
                Logging.Error($"找不到出口IP所在网卡: {e}");
                return false;
            }
        }

19 View Source File : IPAddressExtension.cs
License : Apache License 2.0
Project Creator : alexreinert

public static IPAddress GetNetworkAddress(this IPAddress ipAddress, int netmask)
		{
			if (ipAddress == null)
				throw new ArgumentNullException("ipAddress");

			if ((ipAddress.AddressFamily == AddressFamily.InterNetwork) && ((netmask < 0) || (netmask > 32)))
				throw new ArgumentException("Netmask have to be in range of 0 to 32 on IPv4 addresses", "netmask");

			if ((ipAddress.AddressFamily == AddressFamily.InterNetworkV6) && ((netmask < 0) || (netmask > 128)))
				throw new ArgumentException("Netmask have to be in range of 0 to 128 on IPv6 addresses", "netmask");

			byte[] ipAddressBytes = ipAddress.GetAddressBytes();

			for (int i = 0; i < ipAddressBytes.Length; i++)
			{
				if (netmask >= 8)
				{
					netmask -= 8;
				}
				else
				{
					if (BitConverter.IsLittleEndian)
					{
						ipAddressBytes[i] &= ReverseBitOrder((byte) ~(255 << netmask));
					}
					netmask = 0;
				}
			}

			return new IPAddress(ipAddressBytes);
		}

19 View Source File : WksRecord.cs
License : Apache License 2.0
Project Creator : alexreinert

protected internal override void EncodeRecordData(byte[] messageData, int offset, ref int currentPosition, Dictionary<DomainName, ushort> domainNames, bool useCanonical)
		{
			DnsMessageBase.EncodeByteArray(messageData, ref currentPosition, Address.GetAddressBytes());
			messageData[currentPosition++] = (byte) Protocol;

			foreach (ushort port in Ports)
			{
				int octetPosition = port / 8 + currentPosition;
				int bitPos = port % 8;
				byte octet = messageData[octetPosition];
				octet |= (byte) (1 << Math.Abs(bitPos - 7));
				messageData[octetPosition] = octet;
			}
			currentPosition += Ports.Max() / 8 + 1;
		}

19 View Source File : TimelineSync.cs
License : MIT License
Project Creator : asus4

static bool IsMulticastAddress(IPAddress addr)
        {
            // 224.0.0.0 - 239.255.255.255
            byte[] bytes = addr.GetAddressBytes();
            return (bytes[0] & 0xF0) == 0xE0;
        }

19 View Source File : IPAddressRange.cs
License : GNU General Public License v3.0
Project Creator : aiportal

[Obsolete]
		public static bool Contains(string strRange, string strAddress)
		{
			IPAddressRange range;
			IPAddress address;
			if (TryParse(strRange, out range) && IPAddress.TryParse(strAddress, out address))
			{
				foreach (IPAddress addr in Dns.GetHostEntry(address).AddressList)
				{
					if (addr.AddressFamily == AddressFamily.InterNetwork)
					{
						uint min = BitConverter.ToUInt32(range.AddressMin.GetAddressBytes(), 0);
						uint max = BitConverter.ToUInt32(range.AddressMax.GetAddressBytes(), 0);
						uint ip = BitConverter.ToUInt32(addr.GetAddressBytes(), 0);
						if (min <= ip && ip <= max)
							return true;
					}
				}
			}
			return false;
		}

19 View Source File : Domain.cs
License : GNU General Public License v3.0
Project Creator : BorjaMerino

private static string FormatReverseIP(IPAddress ip) {
            byte[] address = ip.GetAddressBytes();

            if (address.Length == 4) {
                return string.Join(".", address.Reverse().Select(b => b.ToString())) + ".in-addr.arpa";
            }

            byte[] nibbles = new byte[address.Length * 2];

            for (int i = 0, j = 0; i < address.Length; i++, j = 2 * i) {
                byte b = address[i];

                nibbles[j] = b.GetBitValueAt(4, 4);
                nibbles[j + 1] = b.GetBitValueAt(0, 4);
            }

            return string.Join(".", nibbles.Reverse().Select(b => b.ToString("x"))) + ".ip6.arpa";
        }

19 View Source File : MigrationPacket.cs
License : GNU General Public License v3.0
Project Creator : AlanMorel

public static PacketWriter LoginToGame(IPEndPoint endpoint, AuthData authTokens)
    {
        PacketWriter pWriter = PacketWriter.Of(SendOp.LOGIN_TO_GAME);
        pWriter.WriteByte(); // 0 = Success
        pWriter.WriteBytes(endpoint.Address.GetAddressBytes()); // ip
        pWriter.Write((ushort) endpoint.Port); // port
        pWriter.WriteInt(authTokens.TokenA);
        pWriter.WriteInt(authTokens.TokenB); // Some key
        pWriter.WriteInt(62000000); // Map

        return pWriter;
    }

19 View Source File : Message.cs
License : MIT License
Project Creator : aljazsim

public static void Write(byte[] buffer, ref int offset, IPAddress value)
        {
            buffer.CannotBeNullOrEmpty();
            offset.MustBeGreaterThanOrEqualTo(0);
            offset.MustBeLessThan(buffer.Length);
            value.CannotBeNull();

            Write(buffer, ref offset, value.GetAddressBytes());
        }

19 View Source File : IPAddressExtensions.cs
License : Apache License 2.0
Project Creator : alexreinert

public static IPAddress GetNetworkAddress(this IPAddress ipAddress, IPAddress netmask)
		{
			if (ipAddress == null)
				throw new ArgumentNullException(nameof(ipAddress));

			if (netmask == null)
				throw new ArgumentNullException(nameof(netmask));

			if (ipAddress.AddressFamily != netmask.AddressFamily)
				throw new ArgumentOutOfRangeException(nameof(netmask), "Protocoll version of ipAddress and netmask do not match");

			byte[] resultBytes = ipAddress.GetAddressBytes();
			byte[] ipAddressBytes = ipAddress.GetAddressBytes();
			byte[] netmaskBytes = netmask.GetAddressBytes();

			for (int i = 0; i < netmaskBytes.Length; i++)
			{
				resultBytes[i] = (byte) (ipAddressBytes[i] & netmaskBytes[i]);
			}

			return new IPAddress(resultBytes);
		}

19 View Source File : IPAddressExtensions.cs
License : MIT License
Project Creator : albyho

public static int ToInt32(this IPAddress ip)
        {
            var x = 3;
            var v = 0;
            var bytes = ip.GetAddressBytes();
            for (int i = 0; i < bytes.Length; i++)
            {
                byte f = bytes[i];
                v += f << 8 * x--;
            }
            return v;
        }

19 View Source File : SocksReply.cs
License : MIT License
Project Creator : araditc

public byte[] Serialize() {
			byte[] addr;
			if (Address is IPAddress)
				addr = (Address as IPAddress).GetAddressBytes();
			else {
				byte[] domainBytes = Encoding.ASCII.GetBytes((string) Address);
				addr = new byte[domainBytes.Length + 1];
				addr[0] = Convert.ToByte(domainBytes.Length);
				for (int i = 0; i < domainBytes.Length; i++)
					addr[1 + i] = domainBytes[i];
			}
			return new ByteBuilder()
				.Append(version)
				.Append((byte) Status)
				.Append((byte) 0x00)
				.Append((byte) ATyp)
				.Append(addr)
				.Append(Port, bigEndian: true)
				.ToArray();
		}

19 View Source File : IPAddressRange.cs
License : GNU General Public License v3.0
Project Creator : aiportal

public bool Contains(IPAddress addr)
		{
			Debug.replacedert(AddressMin.AddressFamily == AddressFamily.InterNetwork && AddressMax.AddressFamily == AddressFamily.InterNetwork);
			Debug.replacedert(addr.AddressFamily == AddressFamily.InterNetwork);

			uint min = BitConverter.ToUInt32(AddressMin.GetAddressBytes(), 0);
			uint max = BitConverter.ToUInt32(AddressMax.GetAddressBytes(), 0);
			uint ip = BitConverter.ToUInt32(addr.GetAddressBytes(), 0);
			return (min <= ip && ip <= max);
		}

19 View Source File : Socks5Handler.cs
License : MIT License
Project Creator : ARKlab

private byte[] GetEndPointBytes(IPEndPoint remoteEP) {
			if (remoteEP == null)
				throw new ArgumentNullException();
			byte[] connect = new byte[10];
			connect[0] = 5;
			connect[1] = 1;
			connect[2] = 0; //reserved
			connect[3] = 1;
			Array.Copy(remoteEP.Address.GetAddressBytes(), 0, connect, 4, 4);
			Array.Copy(PortToBytes(remoteEP.Port), 0, connect, 8, 2);
			return connect;
		}

19 View Source File : ValidatorBase.cs
License : Apache License 2.0
Project Creator : alexreinert

private async Task<string> ExpandMacroAsync(Match pattern, IPAddress ip, DomainName domain, string sender, CancellationToken token)
		{
			switch (pattern.Value)
			{
				case "%%":
					return "%";
				case "%_":
					return "_";
				case "%-":
					return "-";

				default:
					string letter;
					switch (pattern.Groups["letter"].Value)
					{
						case "s":
							letter = sender;
							break;
						case "l":
							// no boundary check needed, sender is validated on start of CheckHost
							letter = sender.Split('@')[0];
							break;
						case "o":
							// no boundary check needed, sender is validated on start of CheckHost
							letter = sender.Split('@')[1];
							break;
						case "d":
							letter = domain.ToString();
							break;
						case "i":
							letter = String.Join(".", ip.GetAddressBytes().Select(b => b.ToString()));
							break;
						case "p":
							letter = "unknown";

							DnsResolveResult<PtrRecord> dnsResult = await ResolveDnsAsync<PtrRecord>(ip.GetReverseLookupDomain(), RecordType.Ptr, token);
							if ((dnsResult == null) || ((dnsResult.ReturnCode != ReturnCode.NoError) && (dnsResult.ReturnCode != ReturnCode.NxDomain)))
							{
								break;
							}

							int ptrCheckedCount = 0;
							foreach (PtrRecord ptrRecord in dnsResult.Records)
							{
								if (++ptrCheckedCount == 10)
									break;

								bool? isPtrMatch = await IsIpMatchAsync(ptrRecord.PointerDomainName, ip, 0, 0, token);
								if (isPtrMatch.HasValue && isPtrMatch.Value)
								{
									if (letter == "unknown" || ptrRecord.PointerDomainName.IsSubDomainOf(domain))
									{
										// use value, if first record or subdomain
										// but evaluate the other records
										letter = ptrRecord.PointerDomainName.ToString();
									}
									else if (ptrRecord.PointerDomainName.Equals(domain))
									{
										// ptr equal domain --> best match, use it
										letter = ptrRecord.PointerDomainName.ToString();
										break;
									}
								}
							}
							break;
						case "v":
							letter = (ip.AddressFamily == AddressFamily.InterNetworkV6) ? "ip6" : "in-addr";
							break;
						case "h":
							letter = HeloDomain?.ToString() ?? "unknown";
							break;
						case "c":
							IPAddress address =
								LocalIP
								?? NetworkInterface.GetAllNetworkInterfaces()
									.Where(n => (n.OperationalStatus == OperationalStatus.Up) && (n.NetworkInterfaceType != NetworkInterfaceType.Loopback))
									.SelectMany(n => n.GetIPProperties().UnicastAddresses)
									.Select(u => u.Address)
									.FirstOrDefault(a => a.AddressFamily == ip.AddressFamily)
								?? ((ip.AddressFamily == AddressFamily.InterNetwork) ? IPAddress.Loopback : IPAddress.IPv6Loopback);
							letter = address.ToString();
							break;
						case "r":
							letter = LocalDomain?.ToString() ?? System.Net.Dns.GetHostName();
							break;
						case "t":
							letter = ((int) (new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc) - DateTime.Now).TotalSeconds).ToString();
							break;
						default:
							return null;
					}

					// only letter
					if (pattern.Value.Length == 4)
						return letter;

					char[] delimiters = pattern.Groups["delimiter"].Value.ToCharArray();
					if (delimiters.Length == 0)
						delimiters = new[] { '.' };

					string[] parts = letter.Split(delimiters);

					if (pattern.Groups["reverse"].Value == "r")
						parts = parts.Reverse().ToArray();

					int count = Int32.MaxValue;
					if (!String.IsNullOrEmpty(pattern.Groups["count"].Value))
					{
						count = Int32.Parse(pattern.Groups["count"].Value);
					}

					if (count < 1)
						return null;

					count = Math.Min(count, parts.Length);

					return String.Join(".", parts, (parts.Length - count), count);
			}
		}

19 View Source File : IPAddressEx.cs
License : MIT License
Project Creator : Azure

public static IPv4Address AsV4(this IPAddress address) {
            return address == null ? null : new IPv4Address(address.GetAddressBytes());
        }

19 View Source File : AuthenticationDatabase.cs
License : GNU Affero General Public License v3.0
Project Creator : ACEmulator

public Account CreateAccount(string name, string preplacedword, AccessLevel accessLevel, IPAddress address)
        {
            var account = new Account();

            account.AccountName = name;
            account.SetPreplacedword(preplacedword);
            account.SetSaltForBCrypt();
            account.AccessLevel = (uint)accessLevel;

            account.CreateTime = DateTime.UtcNow;
            account.CreateIP = address.GetAddressBytes();

            using (var context = new AuthDbContext())
            {
                context.Account.Add(account);

                context.SaveChanges();
            }

            return account;
        }

19 View Source File : AdminSafeListMiddleware.cs
License : MIT License
Project Creator : bing-framework

public async Task InvokeAsync(HttpContext context)
        {
            if (context.Request.Method != "GET")
            {
                var remoteIp = context.Connection.RemoteIpAddress;
                var log = Log.GetLog(this);
                log.Debug($"来自远程IP地址的请求:{remoteIp}");

                var ips = _whitelist.Split(';');
                var bytes = remoteIp.GetAddressBytes();
                var badIp = true;
                foreach (var ip in ips)
                {
                    var testIp = IPAddress.Parse(ip);
                    if (testIp.GetAddressBytes().SequenceEqual(bytes))
                    {
                        badIp = false;
                        break;
                    }
                }

                if (badIp)
                {
                    log.Info($"来自远程IP地址的禁止请求:{remoteIp}");
                    context.Response.StatusCode = (int)HttpStatusCode.Unauthorized;
                    return;
                }
            }

            await _next.Invoke(context);
        }

19 View Source File : DnsClient.cs
License : Apache License 2.0
Project Creator : alexreinert

public static List<IPAddress> GetLocalConfiguredDnsServers()
		{
			List<IPAddress> res = new List<IPAddress>();

			try
			{
				foreach (NetworkInterface nic in NetworkInterface.GetAllNetworkInterfaces())
				{
					if ((nic.OperationalStatus == OperationalStatus.Up) && (nic.NetworkInterfaceType != NetworkInterfaceType.Loopback))
					{
						foreach (IPAddress dns in nic.GetIPProperties().DnsAddresses)
						{
							// only use servers defined in draft-ietf-ipngwg-dns-discovery if they are in the same subnet
							// fec0::/10 is marked deprecated in RFC 3879, so nobody should use these addresses
							if (dns.AddressFamily == AddressFamily.InterNetworkV6)
							{
								IPAddress unscoped = new IPAddress(dns.GetAddressBytes());
								if (unscoped.Equals(IPAddress.Parse("fec0:0:0:ffff::1"))
								    || unscoped.Equals(IPAddress.Parse("fec0:0:0:ffff::2"))
								    || unscoped.Equals(IPAddress.Parse("fec0:0:0:ffff::3")))
								{
									if (!nic.GetIPProperties().UnicastAddresses.Any(x => x.Address.GetNetworkAddress(10).Equals(IPAddress.Parse("fec0::"))))
										continue;
								}
							}

							if (!res.Contains(dns))
								res.Add(dns);
						}
					}
				}
			}
			catch (Exception e)
			{
				Trace.TraceError("Configured nameserver couldn't be determined: " + e);
			}

			// try parsing resolv.conf since getting data by NetworkInterface is not supported on non-windows mono
			if ((res.Count == 0) && ((Environment.OSVersion.Platform == PlatformID.Unix) || (Environment.OSVersion.Platform == PlatformID.MacOSX)))
			{
				try
				{
					using (StreamReader reader = File.OpenText("/etc/resolv.conf"))
					{
						string line;
						while ((line = reader.ReadLine()) != null)
						{
							int commentStart = line.IndexOf('#');
							if (commentStart != -1)
							{
								line = line.Substring(0, commentStart);
							}

							string[] lineData = line.Split(new[] { ' ', '\t' }, StringSplitOptions.RemoveEmptyEntries);
							IPAddress dns;
							if ((lineData.Length == 2) && (lineData[0] == "nameserver") && (IPAddress.TryParse(lineData[1], out dns)))
							{
								res.Add(dns);
							}
						}
					}
				}
				catch (Exception e)
				{
					Trace.TraceError("/etc/resolv.conf could not be parsed: " + e);
				}
			}

			if (res.Count == 0)
			{
				// fallback: use the public dns-resolvers of google
				res.Add(IPAddress.Parse("2001:4860:4860::8844"));
				res.Add(IPAddress.Parse("2001:4860:4860::8888"));
				res.Add(IPAddress.Parse("8.8.4.4"));
				res.Add(IPAddress.Parse("8.8.8.8"));
			}

			return res.OrderBy(x => x.AddressFamily == AddressFamily.InterNetworkV6 ? 1 : 0).ToList();
		}

19 View Source File : IPAddressExtension.cs
License : Apache License 2.0
Project Creator : alexreinert

public static IPAddress Reverse(this IPAddress ipAddress)
		{
			if (ipAddress == null)
				throw new ArgumentNullException("ipAddress");

			byte[] addressBytes = ipAddress.GetAddressBytes();
			byte[] res = new byte[addressBytes.Length];

			for (int i = 0; i < res.Length; i++)
			{
				res[i] = addressBytes[addressBytes.Length - i - 1];
			}

			return new IPAddress(res);
		}

19 View Source File : GAnalytics.cs
License : GNU General Public License v3.0
Project Creator : AgentRev

public static int GetUniqueID()
        {
            string commentForCodeLurkers = "This is to find the public IPv4 address of the client to use it as unique ID for replacedytics";

            try
            {
                var client = new TimedWebClient();
                var ipAddress = client.DownloadString(ipService);
                ipAddress = Regex.Match(ipAddress, @"([0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3})").Groups[1].Value;

                return BitConverter.ToInt32(IPAddress.Parse(ipAddress).GetAddressBytes(), 0);
            }
            catch
            {
                Random rnd = new Random();
                return rnd.Next(int.MinValue, int.MaxValue);
            }
        }

19 View Source File : IPAddressExtensions.cs
License : Apache License 2.0
Project Creator : alexreinert

public static IPAddress Reverse(this IPAddress ipAddress)
		{
			if (ipAddress == null)
				throw new ArgumentNullException(nameof(ipAddress));

			byte[] addressBytes = ipAddress.GetAddressBytes();
			byte[] res = new byte[addressBytes.Length];

			for (int i = 0; i < res.Length; i++)
			{
				res[i] = addressBytes[addressBytes.Length - i - 1];
			}

			return new IPAddress(res);
		}

19 View Source File : MigrationPacket.cs
License : GNU General Public License v3.0
Project Creator : AlanMorel

public static PacketWriter GameToLogin(IPEndPoint endpoint, AuthData authTokens)
    {
        PacketWriter pWriter = PacketWriter.Of(SendOp.GAME_TO_LOGIN);
        pWriter.WriteByte(); // 0 = Success
        pWriter.WriteBytes(endpoint.Address.GetAddressBytes()); // ip
        pWriter.Write((ushort) endpoint.Port); // port
        pWriter.WriteInt(authTokens.TokenA);
        pWriter.WriteInt(authTokens.TokenB);

        return pWriter;
    }

19 View Source File : IPAddressExtensions.cs
License : Apache License 2.0
Project Creator : alexreinert

public static DomainName GetReverseLookupDomain(this IPAddress ipAddress)
		{
			if (ipAddress == null)
				throw new ArgumentNullException(nameof(ipAddress));

			byte[] addressBytes = ipAddress.GetAddressBytes();

			if (ipAddress.AddressFamily == AddressFamily.InterNetwork)
			{
				string[] labels = new string[addressBytes.Length + 2];

				int labelPos = 0;

				for (int i = addressBytes.Length - 1; i >= 0; i--)
				{
					labels[labelPos++] = addressBytes[i].ToString();
				}

				labels[labelPos++] = "in-addr";
				labels[labelPos] = "arpa";

				return new DomainName(labels);
			}
			else
			{
				string[] labels = new string[addressBytes.Length * 2 + 2];

				int labelPos = 0;

				for (int i = addressBytes.Length - 1; i >= 0; i--)
				{
					string hex = addressBytes[i].ToString("x2");

					labels[labelPos++] = hex[1].ToString();
					labels[labelPos++] = hex[0].ToString();
				}

				labels[labelPos++] = "ip6";
				labels[labelPos] = "arpa";

				return new DomainName(labels);
			}
		}

19 View Source File : IPAddressExtensions.cs
License : Apache License 2.0
Project Creator : alexreinert

public static IPAddress GetNetworkAddress(this IPAddress ipAddress, int netmask)
		{
			if (ipAddress == null)
				throw new ArgumentNullException(nameof(ipAddress));

			if ((ipAddress.AddressFamily == AddressFamily.InterNetwork) && ((netmask < 0) || (netmask > 32)))
				throw new ArgumentException("Netmask have to be in range of 0 to 32 on IPv4 addresses", nameof(netmask));

			if ((ipAddress.AddressFamily == AddressFamily.InterNetworkV6) && ((netmask < 0) || (netmask > 128)))
				throw new ArgumentException("Netmask have to be in range of 0 to 128 on IPv6 addresses", nameof(netmask));

			byte[] ipAddressBytes = ipAddress.GetAddressBytes();

			for (int i = 0; i < ipAddressBytes.Length; i++)
			{
				if (netmask >= 8)
				{
					netmask -= 8;
				}
				else
				{
					if (BitConverter.IsLittleEndian)
					{
						ipAddressBytes[i] &= ReverseBitOrder((byte) ~(255 << netmask));
					}
					netmask = 0;
				}
			}

			return new IPAddress(ipAddressBytes);
		}

19 View Source File : IPAddressExtensions.cs
License : MIT License
Project Creator : albyho

public static long ToInt64(this IPAddress ip)
        {
            int x = 3;
            long v = 0;
            var bytes = ip.GetAddressBytes();
            for (var i = 0; i < bytes.Length; i++)
            {
                byte f = bytes[i];
                v += (long)f << 8 * x--;
            }
            return v;
        }

19 View Source File : AnnounceMessage.cs
License : MIT License
Project Creator : aljazsim

public override int Encode(byte[] buffer, int offset)
        {
            buffer.CannotBeNullOrEmpty();
            offset.MustBeGreaterThanOrEqualTo(0);
            offset.MustBeLessThan(buffer.Length);

            int written = offset;

            Message.Write(buffer, ref written, this.ConnectionId);
            Message.Write(buffer, ref written, (int)this.Action);
            Message.Write(buffer, ref written, this.TransactionId);
            Message.Write(buffer, ref written, this.InfoHash.ToByteArray());
            Message.Write(buffer, ref written, Message.FromPeerId(this.PeerId));
            Message.Write(buffer, ref written, this.Downloaded);
            Message.Write(buffer, ref written, this.Left);
            Message.Write(buffer, ref written, this.Uploaded);
            Message.Write(buffer, ref written, (int)this.TrackingEvent);
            Message.Write(buffer, ref written, this.Endpoint.Address == IPAddress.Loopback ? 0 : BitConverter.ToInt32(this.Endpoint.Address.GetAddressBytes(), 0));
            Message.Write(buffer, ref written, this.Key);
            Message.Write(buffer, ref written, this.NumberWanted);
            Message.Write(buffer, ref written, (ushort)this.Endpoint.Port);

            return written - offset;
        }

19 View Source File : AddressRange.cs
License : GNU General Public License v3.0
Project Creator : aiportal

public static bool Contains(string strRange, string strAddress)
		{
			AddressRange range;
			IPAddress address;
			if (TryParse(strRange, out range) && IPAddress.TryParse(strAddress, out address))
			{
				foreach (IPAddress addr in Dns.GetHostEntry(address).AddressList)
				{
					if (addr.AddressFamily == AddressFamily.InterNetwork)
					{
						uint min = BitConverter.ToUInt32(range.MinAddress.GetAddressBytes(), 0);
						uint max = BitConverter.ToUInt32(range.MaxAddress.GetAddressBytes(), 0);
						uint ip = BitConverter.ToUInt32(addr.GetAddressBytes(), 0);
						if (min <= ip && ip <= max)
							return true;
					}
				}
			}
			return false;
		}

19 View Source File : XdeGuestLocator.cs
License : MIT License
Project Creator : anderm

private static IPAddress GetBroadcastAddressForAddress(IPAddress address, IPAddress mask)
        {
            var addressInt = BitConverter.ToInt32(address.GetAddressBytes(), 0);
            var maskInt = BitConverter.ToInt32(mask.GetAddressBytes(), 0);
            return new IPAddress(BitConverter.GetBytes((addressInt | ~maskInt)));
        }

19 View Source File : IpSecKeyRecord.cs
License : Apache License 2.0
Project Creator : alexreinert

protected internal override void EncodeRecordData(byte[] messageData, int offset, ref int currentPosition, Dictionary<DomainName, ushort> domainNames, bool useCanonical)
		{
			messageData[currentPosition++] = Precedence;
			messageData[currentPosition++] = (byte) GatewayType;
			messageData[currentPosition++] = (byte) Algorithm;
			switch (GatewayType)
			{
				case IpSecGatewayType.IpV4:
				case IpSecGatewayType.IpV6:
					byte[] addressBuffer = IPAddress.Parse(Gateway).GetAddressBytes();
					DnsMessageBase.EncodeByteArray(messageData, ref currentPosition, addressBuffer);
					break;
				case IpSecGatewayType.Domain:
					DnsMessageBase.EncodeDomainName(messageData, offset, ref currentPosition, ParseDomainName(DomainName.Root, Gateway), null, false);
					break;
			}
			DnsMessageBase.EncodeByteArray(messageData, ref currentPosition, PublicKey);
		}

19 View Source File : SocksRequest.cs
License : MIT License
Project Creator : araditc

public byte[] Serialize() {
			byte[] dest;
			if (Destination is IPAddress)
				dest = (Destination as IPAddress).GetAddressBytes();
			else {
				byte[] domainBytes = Encoding.ASCII.GetBytes((string) Destination);
				dest = new byte[domainBytes.Length + 1];
				dest[0] = Convert.ToByte(domainBytes.Length);
				for (int i = 0; i < domainBytes.Length; i++)
					dest[1 + i] = domainBytes[i];
			}
			return new ByteBuilder()
				.Append(version)
				.Append((byte) Command)
				.Append((byte) 0x00)
				.Append((byte) ATyp)
				.Append(dest)
				.Append(Port, bigEndian: true)
				.ToArray();
		}

19 View Source File : AccountExtensions.cs
License : GNU Affero General Public License v3.0
Project Creator : ACEmulator

public static void UpdateLastLogin(this Account account, IPAddress address)
        {
            account.LastLoginIP = address.GetAddressBytes();
            account.LastLoginTime = DateTime.UtcNow;
            account.TotalTimesLoggedIn++;

            DatabaseManager.Authentication.UpdateAccount(account);
        }

19 View Source File : Socks4Handler.cs
License : MIT License
Project Creator : ARKlab

private byte[] GetEndPointBytes(IPEndPoint remoteEP) {
			if (remoteEP == null)
				throw new ArgumentNullException();
			byte[] connect = new byte[9 + Username.Length];
			connect[0] = 4;
			connect[1] = 1;
			Array.Copy(PortToBytes(remoteEP.Port), 0, connect, 2, 2);
			Array.Copy(remoteEP.Address.GetAddressBytes(), 0, connect, 4, 4);
			Array.Copy(Encoding.ASCII.GetBytes(Username), 0, connect, 8, Username.Length);
			connect[8 + Username.Length] = 0;
			return connect;
		}

19 View Source File : AddressRecordBase.cs
License : Apache License 2.0
Project Creator : alexreinert

protected internal override void EncodeRecordData(byte[] messageData, int offset, ref int currentPosition, Dictionary<DomainName, ushort> domainNames, bool useCanonical)
		{
			DnsMessageBase.EncodeByteArray(messageData, ref currentPosition, Address.GetAddressBytes());
		}

19 View Source File : NetDataWriterExtensions.cs
License : MIT License
Project Creator : ash-hat

public static void Put(this NetDataWriter @this, IPAddress value)
		{
			var bytes = value.GetAddressBytes();

			@this.Put((byte) bytes.Length);
			@this.Put(bytes);
		}

19 View Source File : IPAddressRange.cs
License : GNU General Public License v3.0
Project Creator : aiportal

public static bool TryParse(string strRange, out IPAddressRange range)
		{
			range = null;
			if (string.IsNullOrEmpty(strRange))
				return false;

			string[] ss = strRange.Split('-');
			if (ss.Length == 2)
			{
				IPAddress ip1, ip2;
				if (IPAddress.TryParse(ss[0], out ip1) && IPAddress.TryParse(ss[1], out ip2))
				{
					Debug.replacedert(ip1.AddressFamily == AddressFamily.InterNetwork && ip2.AddressFamily == AddressFamily.InterNetwork);
					bool order = BitConverter.ToUInt32(ip1.GetAddressBytes(), 0) < BitConverter.ToUInt32(ip2.GetAddressBytes(), 0);
					range = new IPAddressRange()
					{
						AddressMin = (order ? ip1 : ip2),
						AddressMax = (order ? ip2 : ip1)
					};
					return true;
				}
			}
			return false;
		}

19 View Source File : SubnetTree.cs
License : MIT License
Project Creator : azist

public static IEnumerable<bool> Enumerate(IPAddress address, int CIDR = -1, bool mapToIPv6 = false)
    {
      if (CIDR >= 0 && mapToIPv6 && !IsIPv6(address)) CIDR += CIDRv4Subnet;
      if (mapToIPv6) address = address.MapToIPv6();
      var bytes = address.GetAddressBytes();
      var count = CIDR < 0 ? bytes.Length * 8 : (int)CIDR;
      for (var i = 0; i < count; i++)
        yield return (bytes[i / 8] & (1u << (7 - (i % 8)))) != 0;
    }

19 View Source File : IPAddressExtension.cs
License : Apache License 2.0
Project Creator : alexreinert

public static IPAddress GetNetworkAddress(this IPAddress ipAddress, IPAddress netmask)
		{
			if (ipAddress == null)
				throw new ArgumentNullException("ipAddress");

			if (netmask == null)
				throw new ArgumentNullException("netMask");

			if (ipAddress.AddressFamily != netmask.AddressFamily)
				throw new ArgumentOutOfRangeException("netmask", "Protocoll version of ipAddress and netmask do not match");

			byte[] resultBytes = ipAddress.GetAddressBytes();
			byte[] ipAddressBytes = ipAddress.GetAddressBytes();
			byte[] netmaskBytes = netmask.GetAddressBytes();

			for (int i = 0; i < netmaskBytes.Length; i++)
			{
				resultBytes[i] = (byte) (ipAddressBytes[i] & netmaskBytes[i]);
			}

			return new IPAddress(resultBytes);
		}

19 View Source File : IPAddressEx.cs
License : MIT License
Project Creator : Azure

public static IPAddress Copy(this IPAddress address) {
            return address == null ? null : new IPAddress(address.GetAddressBytes());
        }

19 View Source File : FdbConverters.cs
License : MIT License
Project Creator : abdullin

private static void RegisterDefaultConverters()
		{
			//TODO: there is too much generic type combinations! need to refactor this ...

			RegisterUnsafe<bool, Slice>((value) => Slice.FromByte(value ? (byte)1 : default(byte)));
			RegisterUnsafe<bool, byte[]>((value) => Slice.FromByte(value ? (byte)1 : default(byte)).GetBytes());
			RegisterUnsafe<bool, string>((value) => value ? "true" : "false");
			RegisterUnsafe<bool, sbyte>((value) => value ? (sbyte)1 : default(sbyte));
			RegisterUnsafe<bool, byte>((value) => value ? (byte)1 : default(byte));
			RegisterUnsafe<bool, short>((value) => value ? (short)1 : default(short));
			RegisterUnsafe<bool, ushort>((value) => value ? (ushort)1 : default(ushort));
			RegisterUnsafe<bool, int>((value) => value ? 1 : default(int));
			RegisterUnsafe<bool, uint>((value) => value ? 1U : default(uint));
			RegisterUnsafe<bool, long>((value) => value ? 1L : default(long));
			RegisterUnsafe<bool, ulong>((value) => value ? 1UL : default(ulong));
			RegisterUnsafe<bool, double>((value) => value ? 0.0d : 1.0d);
			RegisterUnsafe<bool, float>((value) => value ? 0.0f : 1.0f);

			RegisterUnsafe<int, Slice>((value) => Slice.FromInt32(value));
			RegisterUnsafe<int, byte[]>((value) => Slice.FromInt32(value).GetBytes());
			RegisterUnsafe<int, string>((value) => value.ToString(CultureInfo.InvariantCulture)); //TODO: string table!
			RegisterUnsafe<int, bool>((value) => value != 0);
			RegisterUnsafe<int, sbyte>((value) => checked((sbyte)value));
			RegisterUnsafe<int, byte>((value) => checked((byte)value));
			RegisterUnsafe<int, short>((value) => checked((short)value));
			RegisterUnsafe<int, ushort>((value) => checked((ushort)value));
			RegisterUnsafe<int, uint>((value) => (uint)value);
			RegisterUnsafe<int, long>((value) => value);
			RegisterUnsafe<int, ulong>((value) => (ulong)value);
			RegisterUnsafe<int, double>((value) => value);
			RegisterUnsafe<int, float>((value) => checked((float)value));
			RegisterUnsafe<int, FdbTupleAlias>((value) => (FdbTupleAlias)value);

			RegisterUnsafe<uint, Slice>((value) => Slice.FromUInt64(value));
			RegisterUnsafe<uint, byte[]>((value) => Slice.FromUInt64(value).GetBytes());
			RegisterUnsafe<uint, string>((value) => value.ToString(CultureInfo.InvariantCulture)); //TODO: string table!
			RegisterUnsafe<uint, bool>((value) => value != 0);
			RegisterUnsafe<uint, sbyte>((value) => checked((sbyte)value));
			RegisterUnsafe<uint, byte>((value) => checked((byte)value));
			RegisterUnsafe<uint, short>((value) => checked((short)value));
			RegisterUnsafe<uint, ushort>((value) => checked((ushort)value));
			RegisterUnsafe<uint, int>((value) => (int)value);
			RegisterUnsafe<uint, long>((value) => value);
			RegisterUnsafe<uint, ulong>((value) => value);
			RegisterUnsafe<uint, double>((value) => value);
			RegisterUnsafe<uint, float>((value) => checked((float)value));

			RegisterUnsafe<long, Slice>((value) => Slice.FromInt64(value));
			RegisterUnsafe<long, byte[]>((value) => Slice.FromInt64(value).GetBytes());
			RegisterUnsafe<long, string>((value) => value.ToString(CultureInfo.InvariantCulture)); //TODO: string table!
			RegisterUnsafe<long, bool>((value) => value != 0);
			RegisterUnsafe<long, sbyte>((value) => checked((sbyte)value));
			RegisterUnsafe<long, byte>((value) => checked((byte)value));
			RegisterUnsafe<long, short>((value) => checked((short)value));
			RegisterUnsafe<long, ushort>((value) => checked((ushort)value));
			RegisterUnsafe<long, int>((value) => checked((int)value));
			RegisterUnsafe<long, uint>((value) => (uint)value);
			RegisterUnsafe<long, ulong>((value) => (ulong)value);
			RegisterUnsafe<long, double>((value) => checked((double)value));
			RegisterUnsafe<long, float>((value) => checked((float)value));
			RegisterUnsafe<long, TimeSpan>((value) => TimeSpan.FromTicks(value));
			RegisterUnsafe<long, Uuid64>((value) => new Uuid64(value));
			RegisterUnsafe<long, System.Net.IPAddress>((value) => new System.Net.IPAddress(value));

			RegisterUnsafe<ulong, Slice>((value) => Slice.FromUInt64(value));
			RegisterUnsafe<ulong, byte[]>((value) => Slice.FromUInt64(value).GetBytes());
			RegisterUnsafe<ulong, string>((value) => value.ToString(CultureInfo.InvariantCulture)); //TODO: string table!
			RegisterUnsafe<ulong, bool>((value) => value != 0);
			RegisterUnsafe<ulong, sbyte>((value) => checked((sbyte)value));
			RegisterUnsafe<ulong, byte>((value) => checked((byte)value));
			RegisterUnsafe<ulong, short>((value) => checked((short)value));
			RegisterUnsafe<ulong, ushort>((value) => checked((ushort)value));
			RegisterUnsafe<ulong, int>((value) => checked((int)value));
			RegisterUnsafe<ulong, uint>((value) => checked((uint)value));
			RegisterUnsafe<ulong, long>((value) => checked((long)value));
			RegisterUnsafe<ulong, double>((value) => checked((double)value));
			RegisterUnsafe<ulong, float>((value) => checked((float)value));
			RegisterUnsafe<ulong, Uuid64>((value) => new Uuid64(value));
			RegisterUnsafe<ulong, TimeSpan>((value) => TimeSpan.FromTicks(checked((long)value)));

			RegisterUnsafe<short, Slice>((value) => Slice.FromInt32(value));
			RegisterUnsafe<short, byte[]>((value) => Slice.FromInt32(value).GetBytes());
			RegisterUnsafe<short, string>((value) => value.ToString(CultureInfo.InvariantCulture)); //TODO: string table!
			RegisterUnsafe<short, bool>((value) => value != 0);
			RegisterUnsafe<short, sbyte>((value) => checked((sbyte)value));
			RegisterUnsafe<short, byte>((value) => checked((byte)value));
			RegisterUnsafe<short, ushort>((value) => checked((ushort)value));
			RegisterUnsafe<short, int>((value) => value);
			RegisterUnsafe<short, uint>((value) => checked((uint)value));
			RegisterUnsafe<short, long>((value) => value);
			RegisterUnsafe<short, ulong>((value) => checked((ulong)value));
			RegisterUnsafe<short, double>((value) => value);
			RegisterUnsafe<short, float>((value) => value);
			RegisterUnsafe<short, FdbTupleAlias>((value) => (FdbTupleAlias)value);

			RegisterUnsafe<ushort, Slice>((value) => Slice.FromUInt64(value));
			RegisterUnsafe<ushort, byte[]>((value) => Slice.FromUInt64(value).GetBytes());
			RegisterUnsafe<ushort, string>((value) => value.ToString(CultureInfo.InvariantCulture)); //TODO: string table!
			RegisterUnsafe<ushort, bool>((value) => value != 0);
			RegisterUnsafe<ushort, byte>((value) => checked((byte)value));
			RegisterUnsafe<ushort, sbyte>((value) => checked((sbyte)value));
			RegisterUnsafe<ushort, short>((value) => checked((short)value));
			RegisterUnsafe<ushort, int>((value) => value);
			RegisterUnsafe<ushort, uint>((value) => value);
			RegisterUnsafe<ushort, long>((value) => value);
			RegisterUnsafe<ushort, ulong>((value) => value);
			RegisterUnsafe<ushort, double>((value) => value);
			RegisterUnsafe<ushort, float>((value) => value);

			RegisterUnsafe<byte, Slice>((value) => Slice.FromInt32(value));
			RegisterUnsafe<byte, byte[]>((value) => Slice.FromInt32(value).GetBytes());
			RegisterUnsafe<byte, string>((value) => value.ToString(CultureInfo.InvariantCulture)); //TODO: string table!
			RegisterUnsafe<byte, bool>((value) => value != 0);
			RegisterUnsafe<byte, sbyte>((value) => checked((sbyte)value));
			RegisterUnsafe<byte, short>((value) => value);
			RegisterUnsafe<byte, ushort>((value) => value);
			RegisterUnsafe<byte, int>((value) => value);
			RegisterUnsafe<byte, uint>((value) => value);
			RegisterUnsafe<byte, long>((value) => value);
			RegisterUnsafe<byte, ulong>((value) => value);
			RegisterUnsafe<byte, double>((value) => value);
			RegisterUnsafe<byte, float>((value) => value);
			RegisterUnsafe<byte, FdbTupleAlias>((value) => (FdbTupleAlias)value);

			RegisterUnsafe<sbyte, Slice>((value) => Slice.FromInt64(value));
			RegisterUnsafe<sbyte, byte[]>((value) => Slice.FromInt64(value).GetBytes());
			RegisterUnsafe<sbyte, string>((value) => value.ToString(CultureInfo.InvariantCulture)); //TODO: string table!
			RegisterUnsafe<sbyte, bool>((value) => value != 0);
			RegisterUnsafe<sbyte, byte>((value) => checked((byte)value));
			RegisterUnsafe<sbyte, short>((value) => value);
			RegisterUnsafe<sbyte, ushort>((value) => checked((ushort)value));
			RegisterUnsafe<sbyte, int>((value) => value);
			RegisterUnsafe<sbyte, uint>((value) => checked((uint)value));
			RegisterUnsafe<sbyte, long>((value) => value);
			RegisterUnsafe<sbyte, ulong>((value) => checked((ulong)value));
			RegisterUnsafe<sbyte, double>((value) => value);
			RegisterUnsafe<sbyte, float>((value) => value);

			RegisterUnsafe<float, Slice>((value) => Slice.FromSingle(value));
			RegisterUnsafe<float, byte[]>((value) => Slice.FromSingle(value).GetBytes());
			RegisterUnsafe<float, string>((value) => value.ToString("R", CultureInfo.InvariantCulture));
			RegisterUnsafe<float, bool>((value) => !(value == 0f || float.IsNaN(value)));
			RegisterUnsafe<float, sbyte>((value) => checked((sbyte)value));
			RegisterUnsafe<float, byte>((value) => checked((byte)value));
			RegisterUnsafe<float, short>((value) => checked((short)value));
			RegisterUnsafe<float, ushort>((value) => checked((ushort)value));
			RegisterUnsafe<float, int>((value) => checked((int)value));
			RegisterUnsafe<float, uint>((value) => (uint)value);
			RegisterUnsafe<float, long>((value) => checked((long)value));
			RegisterUnsafe<float, ulong>((value) => (ulong)value);
			RegisterUnsafe<float, double>((value) => value);

			RegisterUnsafe<double, Slice>((value) => Slice.FromDouble(value));
			RegisterUnsafe<double, byte[]>((value) => Slice.FromDouble(value).GetBytes());
			RegisterUnsafe<double, string>((value) => value.ToString("R", CultureInfo.InvariantCulture));
			RegisterUnsafe<double, bool>((value) => !(value == 0d || double.IsNaN(value)));
			RegisterUnsafe<double, sbyte>((value) => checked((sbyte)value));
			RegisterUnsafe<double, byte>((value) => checked((byte)value));
			RegisterUnsafe<double, short>((value) => checked((short)value));
			RegisterUnsafe<double, ushort>((value) => checked((ushort)value));
			RegisterUnsafe<double, int>((value) => checked((int)value));
			RegisterUnsafe<double, uint>((value) => (uint)value);
			RegisterUnsafe<double, long>((value) => checked((long)value));
			RegisterUnsafe<double, ulong>((value) => (ulong)value);
			RegisterUnsafe<double, float>((value) => checked((float)value));

			RegisterUnsafe<string, Slice>((value) => Slice.FromString(value));
			RegisterUnsafe<string, byte[]>((value) => Slice.FromString(value).GetBytes());
			RegisterUnsafe<string, bool>((value) => !string.IsNullOrEmpty(value));
			RegisterUnsafe<string, sbyte>((value) => string.IsNullOrEmpty(value) ? default(sbyte) : SByte.Parse(value, CultureInfo.InvariantCulture));
			RegisterUnsafe<string, byte>((value) => string.IsNullOrEmpty(value) ? default(byte) : Byte.Parse(value, CultureInfo.InvariantCulture));
			RegisterUnsafe<string, short>((value) => string.IsNullOrEmpty(value) ? default(short) : Int16.Parse(value, CultureInfo.InvariantCulture));
			RegisterUnsafe<string, ushort>((value) => string.IsNullOrEmpty(value) ? default(ushort) : UInt16.Parse(value, CultureInfo.InvariantCulture));
			RegisterUnsafe<string, int>((value) => string.IsNullOrEmpty(value) ? default(int) : Int32.Parse(value, CultureInfo.InvariantCulture));
			RegisterUnsafe<string, uint>((value) => string.IsNullOrEmpty(value) ? default(uint) : UInt32.Parse(value, CultureInfo.InvariantCulture));
			RegisterUnsafe<string, long>((value) => string.IsNullOrEmpty(value) ? default(long) : Int64.Parse(value, CultureInfo.InvariantCulture));
			RegisterUnsafe<string, ulong>((value) => string.IsNullOrEmpty(value) ? default(ulong) : UInt64.Parse(value, CultureInfo.InvariantCulture));
			RegisterUnsafe<string, float>((value) => string.IsNullOrEmpty(value) ? default(float) : Single.Parse(value, NumberStyles.Float, CultureInfo.InvariantCulture));
			RegisterUnsafe<string, double>((value) => string.IsNullOrEmpty(value) ? default(double) : Double.Parse(value, NumberStyles.Float, CultureInfo.InvariantCulture));
			RegisterUnsafe<string, Guid>((value) => string.IsNullOrEmpty(value) ? default(Guid) : Guid.Parse(value));
			RegisterUnsafe<string, Uuid128>((value) => string.IsNullOrEmpty(value) ? default(Uuid128) : Uuid128.Parse(value));
			RegisterUnsafe<string, Uuid64>((value) => string.IsNullOrEmpty(value) ? default(Uuid64) : Uuid64.Parse(value));
			RegisterUnsafe<string, System.Net.IPAddress>((value) => string.IsNullOrEmpty(value) ? default(System.Net.IPAddress) : System.Net.IPAddress.Parse(value));

			RegisterUnsafe<byte[], Slice>((value) => Slice.Create(value));
			RegisterUnsafe<byte[], string>((value) => value == null ? default(string) : value.Length == 0 ? String.Empty : System.Convert.ToBase64String(value));
			RegisterUnsafe<byte[], bool>((value) => value != null && value.Length > 0);
			RegisterUnsafe<byte[], sbyte>((value) => value == null ? default(sbyte) : Slice.Create(value).ToSByte());
			RegisterUnsafe<byte[], byte>((value) => value == null ? default(byte) : Slice.Create(value).ToByte());
			RegisterUnsafe<byte[], short>((value) => value == null ? default(short) : Slice.Create(value).ToInt16());
			RegisterUnsafe<byte[], ushort>((value) => value == null ? default(ushort) : Slice.Create(value).ToUInt16());
			RegisterUnsafe<byte[], int>((value) => value == null ? 0 : Slice.Create(value).ToInt32());
			RegisterUnsafe<byte[], uint>((value) => value == null ? 0U : Slice.Create(value).ToUInt32());
			RegisterUnsafe<byte[], long>((value) => value == null ? 0L : Slice.Create(value).ToInt64());
			RegisterUnsafe<byte[], ulong>((value) => value == null ? 0UL : Slice.Create(value).ToUInt64());
			RegisterUnsafe<byte[], Guid>((value) => value == null || value.Length == 0 ? default(Guid) : new Uuid128(value).ToGuid());
			RegisterUnsafe<byte[], Uuid128>((value) => value == null || value.Length == 0 ? default(Uuid128) : new Uuid128(value));
			RegisterUnsafe<byte[], Uuid64>((value) => value == null || value.Length == 0 ? default(Uuid64) : new Uuid64(value));
			RegisterUnsafe<byte[], TimeSpan>((value) => value == null ? TimeSpan.Zero : TimeSpan.FromTicks(Slice.Create(value).ToInt64()));
			RegisterUnsafe<byte[], System.Net.IPAddress>((value) => value == null || value.Length == 0 ? default(System.Net.IPAddress) : new System.Net.IPAddress(value));

			RegisterUnsafe<Guid, Slice>((value) => Slice.FromGuid(value));
			RegisterUnsafe<Guid, byte[]>((value) => Slice.FromGuid(value).GetBytes());
			RegisterUnsafe<Guid, string>((value) => value.ToString("D", null));
			RegisterUnsafe<Guid, Uuid128>((value) => new Uuid128(value));
			RegisterUnsafe<Guid, bool>((value) => value != Guid.Empty);
			RegisterUnsafe<Guid, System.Net.IPAddress>((value) => new System.Net.IPAddress(new Uuid128(value).ToByteArray()));

			RegisterUnsafe<Uuid128, Slice>((value) => value.ToSlice());
			RegisterUnsafe<Uuid128, byte[]>((value) => value.ToByteArray());
			RegisterUnsafe<Uuid128, string>((value) => value.ToString("D", null));
			RegisterUnsafe<Uuid128, Guid>((value) => value.ToGuid());
			RegisterUnsafe<Uuid128, bool>((value) => value != Uuid128.Empty);
			RegisterUnsafe<Guid, System.Net.IPAddress>((value) => new System.Net.IPAddress(value.ToByteArray()));

			RegisterUnsafe<Uuid64, Slice>((value) => value.ToSlice());
			RegisterUnsafe<Uuid64, byte[]>((value) => value.ToByteArray());
			RegisterUnsafe<Uuid64, string>((value) => value.ToString("D", null));
			RegisterUnsafe<Uuid64, long>((value) => value.ToInt64());
			RegisterUnsafe<Uuid64, ulong>((value) => value.ToUInt64());
			RegisterUnsafe<Uuid64, bool>((value) => value.ToInt64() != 0L);

			RegisterUnsafe<TimeSpan, Slice>((value) => Slice.FromInt64(value.Ticks));
			RegisterUnsafe<TimeSpan, byte[]>((value) => Slice.FromInt64(value.Ticks).GetBytes());
			RegisterUnsafe<TimeSpan, long>((value) => value.Ticks);
			RegisterUnsafe<TimeSpan, ulong>((value) => checked((ulong)value.Ticks));
			RegisterUnsafe<TimeSpan, double>((value) => value.TotalSeconds);
			RegisterUnsafe<TimeSpan, bool>((value) => value == TimeSpan.Zero);

			RegisterUnsafe<System.Net.IPAddress, Slice>((value) => value != null ? Slice.Create(value.GetAddressBytes()) : Slice.Nil);
			RegisterUnsafe<System.Net.IPAddress, byte[]>((value) => value != null ? value.GetAddressBytes() : null);
			RegisterUnsafe<System.Net.IPAddress, string>((value) => value != null ? value.ToString() : null);

			RegisterUnsafe<FdbTupleAlias, byte>((value) => (byte)value);
			RegisterUnsafe<FdbTupleAlias, int>((value) => (int)value);
			RegisterUnsafe<FdbTupleAlias, Slice>((value) => Slice.FromByte((byte)value));

			//REVIEW: this should go in the Tuples layer !
			RegisterUnsafe<Slice, byte[]>((value) => value.GetBytes());
			RegisterUnsafe<Slice, string>((value) => value.ToUnicode());
			RegisterUnsafe<Slice, bool>((value) => value.ToBool());
			RegisterUnsafe<Slice, sbyte>((value) => value.ToSByte());
			RegisterUnsafe<Slice, byte>((value) => value.ToByte());
			RegisterUnsafe<Slice, short>((value) => value.ToInt16());
			RegisterUnsafe<Slice, ushort>((value) => value.ToUInt16());
			RegisterUnsafe<Slice, int>((value) => value.ToInt32());
			RegisterUnsafe<Slice, uint>((value) => value.ToUInt32());
			RegisterUnsafe<Slice, long>((value) => value.ToInt64());
			RegisterUnsafe<Slice, ulong>((value) => value.ToUInt64());
			RegisterUnsafe<Slice, Guid>((value) => value.ToGuid());
			RegisterUnsafe<Slice, Uuid128>((value) => value.ToUuid128());
			RegisterUnsafe<Slice, Uuid64>((value) => value.ToUuid64());
			RegisterUnsafe<Slice, TimeSpan>((value) => TimeSpan.FromTicks(value.ToInt64()));
			RegisterUnsafe<Slice, FdbTupleAlias>((value) => (FdbTupleAlias)value.ToByte());
			RegisterUnsafe<Slice, System.Net.IPAddress>((value) => !value.IsNullOrEmpty ? new System.Net.IPAddress(value.GetBytes()) : null);
		}

19 View Source File : CrawlerHandler.cs
License : MIT License
Project Creator : baiyunchen

private bool IsPrivateIP(IPAddress myIpAddress)
        {
            if (IPAddress.IsLoopback(myIpAddress)) return true;
            if (myIpAddress.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)
            {
                byte[] ipBytes = myIpAddress.GetAddressBytes();
                // 10.0.0.0/24 
                if (ipBytes[0] == 10)
                {
                    return true;
                }
                // 172.16.0.0/16
                else if (ipBytes[0] == 172 && ipBytes[1] == 16)
                {
                    return true;
                }
                // 192.168.0.0/16
                else if (ipBytes[0] == 192 && ipBytes[1] == 168)
                {
                    return true;
                }
                // 169.254.0.0/16
                else if (ipBytes[0] == 169 && ipBytes[1] == 254)
                {
                    return true;
                }
            }
            return false;
        }

19 View Source File : ClientSubnetOption.cs
License : Apache License 2.0
Project Creator : alexreinert

internal override void EncodeData(byte[] messageData, ref int currentPosition)
		{
			DnsMessageBase.EncodeUShort(messageData, ref currentPosition, (ushort) (Family == AddressFamily.InterNetwork ? 1 : 2));
			messageData[currentPosition++] = SourceNetmask;
			messageData[currentPosition++] = ScopeNetmask;

			byte[] data = Address.GetAddressBytes();
			DnsMessageBase.EncodeByteArray(messageData, ref currentPosition, data, GetAddressLength());
		}

19 View Source File : AccessPolicy.cs
License : GNU General Public License v3.0
Project Creator : aiportal

private PhysicalAddress GetMacAddress(IPAddress remoteAddr)
		{
			Debug.replacedert(remoteAddr.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork);

			int ip = BitConverter.ToInt32(remoteAddr.GetAddressBytes(), 0);
			int length = 6;
			byte[] bs = new byte[length];
			SendARP(ip, 0, bs, ref length);
			return new PhysicalAddress(bs);
		}

19 View Source File : IPHelper.cs
License : MIT License
Project Creator : 1100100

private static long ConvertIpToNumber(IPAddress ipAddress)
        {
            var bytes = ipAddress.GetAddressBytes();
            return bytes[0] * 256 * 256 * 256 + bytes[1] * 256 * 256 + bytes[2] * 256 + bytes[3];
        }

19 View Source File : FdbTuplePackers.cs
License : MIT License
Project Creator : abdullin

public static void SerializeTo(ref TupleWriter writer, System.Net.IPAddress value)
		{
			FdbTupleParser.WriteBytes(ref writer, value != null ? value.GetAddressBytes() : null);
		}

19 View Source File : AddressRange.cs
License : GNU General Public License v3.0
Project Creator : aiportal

public static bool TryParse(string strRange, out AddressRange range)
		{
			range = null;
			if (!string.IsNullOrEmpty(strRange) && strRange.Contains("-"))
			{
				string[] ss = strRange.Split('-');
				if (ss.Length == 2)
				{
					IPAddress ip1, ip2;
					if (IPAddress.TryParse(ss[0], out ip1) && IPAddress.TryParse(ss[1], out ip2))
					{
						if (BitConverter.ToUInt32(ip1.GetAddressBytes(), 0) < BitConverter.ToUInt32(ip2.GetAddressBytes(), 0))
						{
							range = new AddressRange()
							{
								MinAddress = ip1,
								MaxAddress = ip2
							};
						}
						else
						{
							range = new AddressRange()
							{
								MinAddress = ip2,
								MaxAddress = ip1
							};
						}
						return true;
					}
				}
			}
			return false;
		}

19 View Source File : MigrationPacket.cs
License : GNU General Public License v3.0
Project Creator : AlanMorel

public static PacketWriter GameToGame(IPEndPoint endpoint, AuthData authTokens, Player player)
    {
        PacketWriter pWriter = PacketWriter.Of(SendOp.GAME_TO_GAME);
        pWriter.WriteByte(); // 0 = Success
        pWriter.WriteInt(authTokens.TokenA);
        pWriter.WriteInt(authTokens.TokenB);
        pWriter.WriteBytes(endpoint.Address.GetAddressBytes());
        pWriter.Write((ushort) endpoint.Port);
        pWriter.WriteInt(player.MapId); // Map
        pWriter.WriteByte(); //unknown

        return pWriter;
    }

19 View Source File : IPAddressExtensions.cs
License : Apache License 2.0
Project Creator : alexreinert

public static string GetReverseLookupAddress(this IPAddress ipAddress)
		{
			if (ipAddress == null)
				throw new ArgumentNullException(nameof(ipAddress));

			StringBuilder res = new StringBuilder();

			byte[] addressBytes = ipAddress.GetAddressBytes();

			if (ipAddress.AddressFamily == AddressFamily.InterNetwork)
			{
				for (int i = addressBytes.Length - 1; i >= 0; i--)
				{
					res.Append(addressBytes[i]);
					res.Append(".");
				}
				res.Append("in-addr.arpa");
			}
			else
			{
				for (int i = addressBytes.Length - 1; i >= 0; i--)
				{
					string hex = addressBytes[i].ToString("x2");
					res.Append(hex[1]);
					res.Append(".");
					res.Append(hex[0]);
					res.Append(".");
				}

				res.Append("ip6.arpa");
			}

			return res.ToString();
		}

See More Examples