System.Net.IPAddress.TryParse(string, out System.Net.IPAddress)

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

666 Examples 7

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

public async Task<IClient> CreateClientAsync(string serviceName, ServiceNodeInfo nodeInfo)
        {
            var key = (nodeInfo.Address, nodeInfo.Port);
            try
            {
                return await _clients.GetOrAdd(key, async k =>
                {
                    IEventLoopGroup group;
                    var bootstrap = new Bootstrap();
                    if (UraganoOptions.DotNetty_Enable_Libuv.Value)
                    {
                        group = new EventLoopGroup();
                        bootstrap.Channel<TcpChannel>();
                    }
                    else
                    {
                        group = new MulreplacedhreadEventLoopGroup();
                        bootstrap.Channel<TcpSocketChannel>();
                    }

                    bootstrap
                        .Group(group)
                        .Option(ChannelOption.TcpNodelay, true)
                        .Option(ChannelOption.Allocator, PooledByteBufferAllocator.Default)
                        .Option(ChannelOption.ConnectTimeout, UraganoOptions.DotNetty_Connect_Timeout.Value)
                        .Handler(new ActionChannelInitializer<IChannel>(ch =>
                        {
                            var pipeline = ch.Pipeline;
                            if (nodeInfo.EnableTls)
                            {
                                var cert = ClientSettings?.ServicesCert?.FirstOrDefault(p => p.Key == serviceName).Value ?? ClientSettings?.DefaultCert;
                                if (cert == null)
                                {
                                    Logger.LogError($"Service {serviceName}[{nodeInfo.Address}:{nodeInfo.Port}] has TLS enabled, please configure the certificate.");
                                    throw new InvalidOperationException(
                                        $"Service {serviceName}[{nodeInfo.Address}:{nodeInfo.Port}] has TLS enabled, please configure the certificate.");
                                }

                                var targetHost = cert.Cert.GetNameInfo(X509NameType.DnsName, false);
                                pipeline.AddLast(new TlsHandler(stream =>
                                {
                                    return new SslStream(stream, true,
                                        (sender, certificate, chain, errors) =>
                                        {
                                            var successful = SslPolicyErrors.None == errors;
                                            if (!successful)
                                                Logger.LogError("The remote certificate is invalid according to the validation procedure:{0}.", errors);
                                            return successful;
                                        });
                                }, new ClientTlsSettings(targetHost)));
                            }

                            //pipeline.AddLast(new LoggingHandler("SRV-CONN"));
                            pipeline.AddLast(new LengthFieldPrepender(4));
                            pipeline.AddLast(new LengthFieldBasedFrameDecoder(int.MaxValue, 0, 4, 0, 4));
                            pipeline.AddLast(new MessageDecoder<IServiceResult>(Codec));
                            pipeline.AddLast(new MessageEncoder<IInvokeMessage>(Codec));
                            pipeline.AddLast(new ClientMessageHandler(this));
                        }));

                    EndPoint endPoint;
                    if (IPAddress.TryParse(nodeInfo.Address, out var ip))
                        endPoint = new IPEndPoint(ip, nodeInfo.Port);
                    else
                        endPoint = new DnsEndPoint(nodeInfo.Address, nodeInfo.Port);
                    var channel = await bootstrap.ConnectAsync(endPoint);
                    channel.GetAttribute(TransportContextAttributeKey).Set(new TransportContext
                    {
                        Host = nodeInfo.Address,
                        Port = nodeInfo.Port
                    });

                    var listener = new MessageListener();
                    channel.GetAttribute(MessageListenerAttributeKey).Set(listener);
                    return new Client(channel, group, listener, Logger, Codec, $"{nodeInfo.Address}:{ nodeInfo.Port}");
                });
            }
            catch
            {
                _clients.TryRemove(key, out _);
                throw;
            }
        }

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

public async Task StartAsync()
        {
            try
            {
                var bootstrap = new DotNetty.Transport.Bootstrapping.ServerBootstrap();
                if (UraganoOptions.DotNetty_Enable_Libuv.Value)
                {
                    var dispatcher = new DispatcherEventLoopGroup();
                    BossGroup = dispatcher;
                    WorkerGroup = new WorkerEventLoopGroup(dispatcher);
                    bootstrap.Channel<TcpServerChannel>();
                }
                else
                {
                    BossGroup = new MulreplacedhreadEventLoopGroup(1);
                    WorkerGroup = new MulreplacedhreadEventLoopGroup(UraganoOptions.DotNetty_Event_Loop_Count.Value);
                    bootstrap.Channel<TcpServerSocketChannel>();
                }

                bootstrap
                    .Group(BossGroup, WorkerGroup)
                    .Option(ChannelOption.SoBacklog, UraganoOptions.Server_DotNetty_Channel_SoBacklog.Value)
                    .ChildOption(ChannelOption.Allocator, PooledByteBufferAllocator.Default)
                    .ChildOption(ChannelOption.ConnectTimeout, UraganoOptions.DotNetty_Connect_Timeout.Value)
                    .ChildHandler(new ActionChannelInitializer<IChannel>(channel =>
                    {
                        var pipeline = channel.Pipeline;
                        if (ServerSettings.X509Certificate2 != null)
                        {
                            pipeline.AddLast(TlsHandler.Server(ServerSettings.X509Certificate2));
                        }

                        //pipeline.AddLast(new LoggingHandler("SRV-CONN"));
                        pipeline.AddLast(new LengthFieldPrepender(4));
                        pipeline.AddLast(new LengthFieldBasedFrameDecoder(int.MaxValue, 0, 4, 0, 4));
                        pipeline.AddLast(new MessageDecoder<IInvokeMessage>(Codec));
                        pipeline.AddLast(new MessageEncoder<IServiceResult>(Codec));
                        pipeline.AddLast(new ServerMessageHandler(ServiceFactory, ServiceProvider, Logger, Codec, ServerSettings));
                    }));

                EndPoint endPoint;
                if (IPAddress.TryParse(ServerSettings.Address, out var iPAddress))
                    endPoint = new IPEndPoint(iPAddress, ServerSettings.Port);
                else
                    endPoint = new DnsEndPoint(ServerSettings.Address, ServerSettings.Port);
                Channel = await bootstrap.BindAsync(endPoint);
                Logger.LogInformation($"Uragano server listening {ServerSettings}");
            }
            catch (Exception e)
            {
                Logger.LogError(e, $"Start server[{ServerSettings}] failed!");
            }
        }

19 View Source File : UriEx.cs
License : MIT License
Project Creator : 1iveowl

public static IPAddress GetIPv4Address(this string ipAddress)
        {
            if (IPAddress.TryParse(ipAddress, out var address))
            {
                return address.MapToIPv4();
            }
            else
            {
                return Dns.GetHostAddresses(ipAddress).FirstOrDefault()?.MapToIPv4();
            }
            
        }

19 View Source File : ClientInfo.cs
License : MIT License
Project Creator : 1ZouLTReX1

public void OnTextChanged(TMPro.TMP_InputField newValue)
    {
        string newIpString = newValue.text;

        if (newIpString == "" || !IPAddress.TryParse(newIpString, out ipAddress))
            ipAddress = Globals.GetLocalIPAddress();
        
        remoteEP = new IPEndPoint(ipAddress, port);
        Debug.Log(remoteEP.Address + " : " + remoteEP.Port);
    }

19 View Source File : UriEx.cs
License : MIT License
Project Creator : 1iveowl

public static IPAddress GetIPv6Address(this string ipAddress)
        {
            if (IPAddress.TryParse(ipAddress, out var address))
            {
                return address.MapToIPv6();
            }
            else
            {
                return Dns.GetHostAddresses(ipAddress).FirstOrDefault()?.MapToIPv6();
            }

        }

19 View Source File : RedisClientPool.cs
License : MIT License
Project Creator : 2881099

internal void SetHost(string host)
        {
            if (string.IsNullOrEmpty(host?.Trim())) {
                _ip = "127.0.0.1";
                _port = 6379;
                return;
            }
            host = host.Trim();
            var ipv6 = Regex.Match(host, @"^\[([^\]]+)\]\s*(:\s*(\d+))?$");
            if (ipv6.Success) //ipv6+port 格式: [fe80::b164:55b3:4b4f:7ce6%15]:6379
            {
                _ip = ipv6.Groups[1].Value.Trim();
                _port = int.TryParse(ipv6.Groups[3].Value, out var tryint) && tryint > 0 ? tryint : 6379;
                return;
            }
            var spt = (host ?? "").Split(':');
            if (spt.Length == 1) //ipv4 or domain
            {
                _ip = string.IsNullOrEmpty(spt[0].Trim()) == false ? spt[0].Trim() : "127.0.0.1";
                _port = 6379;
                return;
            }
            if (spt.Length == 2) //ipv4:port or domain:port
            {
                if (int.TryParse(spt.Last().Trim(), out var testPort2))
                {
                    _ip = string.IsNullOrEmpty(spt[0].Trim()) == false ? spt[0].Trim() : "127.0.0.1";
                    _port = testPort2;
                    return;
                }
                _ip = host;
                _port = 6379;
                return;
            }
            if (IPAddress.TryParse(host, out var tryip) && tryip.AddressFamily == AddressFamily.InterNetworkV6) //test ipv6
            {
                _ip = host;
                _port = 6379;
                return;
            }
            if (int.TryParse(spt.Last().Trim(), out var testPort)) //test ipv6:port
            {
                var testHost = string.Join(":", spt.Where((a, b) => b < spt.Length - 1));
                if (IPAddress.TryParse(testHost, out tryip) && tryip.AddressFamily == AddressFamily.InterNetworkV6)
                {
                    _ip = testHost;
                    _port = 6379;
                    return;
                }
            }
            _ip = host;
            _port = 6379;
        }

19 View Source File : RedisClientPool.cs
License : MIT License
Project Creator : 2881099

public RedisClient OnCreate()
        {
            RedisClient client = null;
            if (IPAddress.TryParse(_ip, out var tryip))
            {
                client = new RedisClient(new IPEndPoint(tryip, _port), _ssl);
            }
            else
            {
                var ips = Dns.GetHostAddresses(_ip);
                if (ips.Length == 0) throw new Exception($"无法解析“{_ip}”");
                client = new RedisClient(_ip, _port, _ssl);
            }
            client.Connected += (s, o) =>
            {
                Connected(s, o);
                if (!string.IsNullOrEmpty(_clientname)) client.ClientSetName(_clientname);
            };
            return client;
        }

19 View Source File : DefaultRedisSocket.cs
License : MIT License
Project Creator : 2881099

public static KeyValuePair<string, int> SplitHost(string host)
        {
            if (string.IsNullOrWhiteSpace(host?.Trim()))
                return new KeyValuePair<string, int>("127.0.0.1", 6379);

            host = host.Trim();
            var ipv6 = Regex.Match(host, @"^\[([^\]]+)\]\s*(:\s*(\d+))?$");
            if (ipv6.Success) //ipv6+port 格式: [fe80::b164:55b3:4b4f:7ce6%15]:6379
                return new KeyValuePair<string, int>(ipv6.Groups[1].Value.Trim(), 
                    int.TryParse(ipv6.Groups[3].Value, out var tryint) && tryint > 0 ? tryint : 6379);

            var spt = (host ?? "").Split(':');
            if (spt.Length == 1) //ipv4 or domain
                return new KeyValuePair<string, int>(string.IsNullOrWhiteSpace(spt[0].Trim()) == false ? spt[0].Trim() : "127.0.0.1", 6379);

            if (spt.Length == 2) //ipv4:port or domain:port
            {
                if (int.TryParse(spt.Last().Trim(), out var testPort2))
                    return new KeyValuePair<string, int>(string.IsNullOrWhiteSpace(spt[0].Trim()) == false ? spt[0].Trim() : "127.0.0.1", testPort2);

                return new KeyValuePair<string, int>(host, 6379);
            }

            if (IPAddress.TryParse(host, out var tryip) && tryip.AddressFamily == AddressFamily.InterNetworkV6) //test ipv6
                return new KeyValuePair<string, int>(host, 6379);

            if (int.TryParse(spt.Last().Trim(), out var testPort)) //test ipv6:port
            {
                var testHost = string.Join(":", spt.Where((a, b) => b < spt.Length - 1));
                if (IPAddress.TryParse(testHost, out tryip) && tryip.AddressFamily == AddressFamily.InterNetworkV6)
                    return new KeyValuePair<string, int>(testHost, 6379);
            }

            return new KeyValuePair<string, int>(host, 6379);
        }

19 View Source File : SftpForm.cs
License : Apache License 2.0
Project Creator : 214175590

private void toolStripButton7_Click(object sender, EventArgs e)
        {
            string host = text_host.Text;
            string username = text_username.Text;
            string preplaced = text_preplaced.Text;
            string port = text_port.Text;

            IPAddress ip;
            if (IPAddress.TryParse(host, out ip))
            {
                if(string.IsNullOrWhiteSpace(username)){
                    MessageBox.Show(this, "请输入用户名");
                }
                else if (string.IsNullOrWhiteSpace(preplaced))
                {
                    MessageBox.Show(this, "请输入密码");
                }
                else if (string.IsNullOrWhiteSpace(port))
                {
                    MessageBox.Show(this, "请输入端口号");
                }
                else
                {
                    user.Host = host;
                    user.UserName = username;
                    user.Preplacedword = YSEncrypt.EncryptA(preplaced, KeysUtil.PreplacedKey);
                    user.Port = Convert.ToInt32(port);

                    LoadRightForm(user);
                }
            }
            else
            {
                MessageBox.Show(this, "Host地址不正确");
            }
        }

19 View Source File : DefaultRedisSocket.cs
License : MIT License
Project Creator : 2881099

public void Connect()
        {
            lock (_connectLock)
            {
                ResetHost(Host);

                IPEndPoint endpoint = IPAddress.TryParse(_ip, out var tryip) ?
                    new IPEndPoint(tryip, _port) :
                    new IPEndPoint(Dns.GetHostAddresses(_ip).FirstOrDefault() ?? IPAddress.Parse(_ip), _port);
                var localSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

                var asyncResult = localSocket.BeginConnect(endpoint, null, null);
                if (!asyncResult.AsyncWaitHandle.WaitOne(ConnectTimeout, true))
                    throw new TimeoutException("Connect to redis-server timeout");
                _socket = localSocket;
                _stream = new NetworkStream(Socket, true);
                _socket.ReceiveTimeout = (int)ReceiveTimeout.TotalMilliseconds;
                _socket.SendTimeout = (int)SendTimeout.TotalMilliseconds;
                Connected?.Invoke(this, new EventArgs());
            }
        }

19 View Source File : Utils.cs
License : GNU General Public License v3.0
Project Creator : 2dust

public static bool IsIpv6(string ip)
        {
            IPAddress address;
            if (IPAddress.TryParse(ip, out address))
            {
                switch (address.AddressFamily)
                {
                    case AddressFamily.InterNetwork:
                        return false;
                    case AddressFamily.InterNetworkV6:
                        return true;
                    default:
                        return false;
                }
            }
            return false;
        }

19 View Source File : SpeedtestHandler.cs
License : GNU General Public License v3.0
Project Creator : 2dust

private int GetTcpingTime(string url, int port)
        {
            int responseTime = -1;

            try
            {
                if (!IPAddress.TryParse(url, out IPAddress ipAddress))
                {
                    IPHostEntry ipHostInfo = System.Net.Dns.GetHostEntry(url);
                    ipAddress = ipHostInfo.AddressList[0];
                }

                Stopwatch timer = new Stopwatch();
                timer.Start();

                IPEndPoint endPoint = new IPEndPoint(ipAddress, port);
                Socket clientSocket = new Socket(endPoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp);

                IAsyncResult result = clientSocket.BeginConnect(endPoint, null, null);
                if (!result.AsyncWaitHandle.WaitOne(TimeSpan.FromSeconds(5)))
                    throw new TimeoutException("connect timeout (5s): " + url);
                clientSocket.EndConnect(result);

                timer.Stop();
                responseTime = timer.Elapsed.Milliseconds;
                clientSocket.Close();
            }
            catch (Exception ex)
            {
                Utils.SaveLog(ex.Message, ex);
            }
            return responseTime;
        }

19 View Source File : SCC.cs
License : Apache License 2.0
Project Creator : AantCoder

public static string Login(string addr, string login, string preplacedword)
        {
            var StrIp = addr.Split(':');
            var port = Transfer.SessionClient.DefaultPort;
            if (StrIp.Length == 2)
            {
                if (!int.TryParse(StrIp[1], out port))
                {
                    return "Invalid IP adress or port";
                }
            }

            if (!IPAddress.TryParse(StrIp[0],out IPAddress ipAdres))
            {
                return "Invalid IP adress";
            }

            var endPoint = new IPEndPoint(ipAdres, port);

            return ChatProv.Login(endPoint, login, preplacedword);
        }

19 View Source File : Helper.cs
License : Apache License 2.0
Project Creator : AantCoder

public static IPEndPoint TryParseStringToIp(string value)
        {
            if (string.IsNullOrWhiteSpace(value))
            {
                return null;
            }

            int port;
            var lastIndex = value.IndexOf(":");
            if (lastIndex > 0)
            {
                var strPort = value.Substring(lastIndex + 1);
                if (!int.TryParse(strPort, out port) || port < IPEndPoint.MinPort || port > IPEndPoint.MaxPort)
                {
                    return null;
                }
            }
            else
            {
                port = Transfer.SessionClient.DefaultPort;
            }

            lastIndex = lastIndex > 0 ? lastIndex : value.Length;
            var ipString = value.Substring(0, lastIndex);

            if (!IPAddress.TryParse(ipString, out IPAddress ip))
            {
                return null;
            }

            return new IPEndPoint(ip, port);
        }

19 View Source File : ServiceDefinitionPortalBusProvider.cs
License : MIT License
Project Creator : Adoxio

protected override async Task SendRemoteAsync(IOwinContext context, TMessage message)
		{
			IPAddress localAddress = null;

			if (context != null)
			{
				IPAddress.TryParse(context.Environment["server.LocalIpAddress"] as string ?? string.Empty, out localAddress);
			}

			var roles = GetRoles(FullServiceDefinition, false);
			var sites = FullServiceDefinition.CurrentRole.Sites;

			// send the message

			await SendRequest(roles, sites, localAddress, Options.InternalEndpointName, message).WithCurrentCulture();
		}

19 View Source File : GrpcUriHelper.cs
License : MIT License
Project Creator : AElfProject

public static bool TryParsePrefixedEndpoint(string url, out IPEndPoint endPoint)
        {
            endPoint = null;
            
            var splitRes = url.Split(':');

            if (splitRes.Length != 3)
                return false;

            if (!IPAddress.TryParse(splitRes[1], out IPAddress parsedAddress))
                return false;

            if (!int.TryParse(splitRes[2], out int parsedPort))
                return false;

            endPoint = new IPEndPoint(parsedAddress, parsedPort);

            return true;
        }

19 View Source File : Client.cs
License : Apache License 2.0
Project Creator : aequabit

public void Connect(string host, ushort port)
    {
        try
        {
            Disconnect();
            Initialize();

            IPAddress IP = IPAddress.None;
            if (IPAddress.TryParse(host, out IP))
            {
                DoConnect(IP, port);
            }
            else
            {
                Dns.BeginGetHostEntry(host, EndGetHostEntry, port);
            }
        }
        catch (Exception ex)
        {
            O.Post(x => OnExceptionThrown((Exception)x), ex);
            Disconnect();
        }
    }

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 : 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 : 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 : 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 : HttpContextExtensions.cs
License : MIT License
Project Creator : albyho

public static IPAddress GetRealIp(this HttpContext context)
        {
            IPAddress ip;
            var headers = context.Request.Headers;
            if (!headers.ContainsKey("X-Forwarded-For") || !IPAddress.TryParse(headers["X-Forwarded-For"].ToString().Split(',')[0], out ip))
            {
                ip = context.Connection.RemoteIpAddress;
            }
            return ip;
        }

19 View Source File : PerformanceTestsRunner.cs
License : MIT License
Project Creator : alelievr

static void ReportPerformaces(List< PerformanceResultMulti > resultsList)
		{
			string ip = Environment.GetEnvironmentVariable("PW_REPORT_IP");

			if (String.IsNullOrEmpty(ip))
			{
				logFile.WriteLine("PW_REPORT_IP environement variable is empty !");
				return ;
			}

			IPAddress ipa;
			IPAddress.TryParse(ip, out ipa);

			if (ipa == null)
			{
				logFile.WriteLine("Can't parse IP: " + ip);
				return ;
			}
			
			try {
				IPEndPoint ipe = new IPEndPoint(ipa, 4204);
				Socket s = new Socket(ipe.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
				s.Connect(ipe);
	
				if (!s.Connected)
				{
					logFile.WriteLine("Can't connect the socket !");
					return ;
				}
	
				Stream stream = new NetworkStream(s);
				var bin = new BinaryFormatter();

				bin.Serialize(stream, resultsList.ToArray());
			} catch (Exception e) {
				logFile.WriteLine("An error occured: " + e);
			}
		}

19 View Source File : FormatValidation.cs
License : MIT License
Project Creator : alethic

public static bool ValidateIPv6(string value)
        {
            return Uri.CheckHostName(value) == UriHostNameType.IPv6 && IPAddress.TryParse(value, out var ip) && ip.AddressFamily == AddressFamily.InterNetworkV6 && value.Contains("%") == false;
        }

19 View Source File : RemoteAddress.cs
License : MIT License
Project Creator : alexleen

public override bool TryValidate(IMessageBoxService messageBoxService)
        {
            if (!IPAddress.TryParse(Value, out _))
            {
                messageBoxService.ShowError("Remote address must be a valid IP address.");
                return false;
            }

            return base.TryValidate(messageBoxService);
        }

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 : ValidatorBase.cs
License : Apache License 2.0
Project Creator : alexreinert

private async Task<SpfQualifier> CheckMechanismAsync(SpfMechanism mechanism, IPAddress ip, DomainName domain, string sender, State state, CancellationToken token)
		{
			switch (mechanism.Type)
			{
				case SpfMechanismType.All:
					return mechanism.Qualifier;

				case SpfMechanismType.A:
					if (++state.DnsLookupCount > 10)
						return SpfQualifier.PermError;

					DomainName aMechanismDomain = String.IsNullOrEmpty(mechanism.Domain) ? domain : await ExpandDomainAsync(mechanism.Domain, ip, domain, sender, token);

					bool? isAMatch = await IsIpMatchAsync(aMechanismDomain, ip, mechanism.Prefix, mechanism.Prefix6, token);
					if (!isAMatch.HasValue)
						return SpfQualifier.TempError;

					if (isAMatch.Value)
					{
						return mechanism.Qualifier;
					}
					break;

				case SpfMechanismType.Mx:
					if (++state.DnsLookupCount > 10)
						return SpfQualifier.PermError;

					DomainName mxMechanismDomain = String.IsNullOrEmpty(mechanism.Domain) ? domain : await ExpandDomainAsync(mechanism.Domain, ip, domain, sender, token);

					DnsResolveResult<MxRecord> dnsMxResult = await ResolveDnsAsync<MxRecord>(mxMechanismDomain, RecordType.Mx, token);
					if ((dnsMxResult == null) || ((dnsMxResult.ReturnCode != ReturnCode.NoError) && (dnsMxResult.ReturnCode != ReturnCode.NxDomain)))
						return SpfQualifier.TempError;

					int mxCheckedCount = 0;

					foreach (MxRecord mxRecord in dnsMxResult.Records)
					{
						if (++mxCheckedCount == 10)
							break;

						bool? isMxMatch = await IsIpMatchAsync(mxRecord.ExchangeDomainName, ip, mechanism.Prefix, mechanism.Prefix6, token);
						if (!isMxMatch.HasValue)
							return SpfQualifier.TempError;

						if (isMxMatch.Value)
						{
							return mechanism.Qualifier;
						}
					}
					break;

				case SpfMechanismType.Ip4:
				case SpfMechanismType.Ip6:
					IPAddress compareAddress;
					if (IPAddress.TryParse(mechanism.Domain, out compareAddress))
					{
						if (ip.AddressFamily != compareAddress.AddressFamily)
							return SpfQualifier.None;

						if (mechanism.Prefix.HasValue)
						{
							if ((mechanism.Prefix.Value < 0) || (mechanism.Prefix.Value > (compareAddress.AddressFamily == AddressFamily.InterNetworkV6 ? 128 : 32)))
								return SpfQualifier.PermError;

							if (ip.GetNetworkAddress(mechanism.Prefix.Value).Equals(compareAddress.GetNetworkAddress(mechanism.Prefix.Value)))
							{
								return mechanism.Qualifier;
							}
						}
						else if (ip.Equals(compareAddress))
						{
							return mechanism.Qualifier;
						}
					}
					else
					{
						return SpfQualifier.PermError;
					}

					break;

				case SpfMechanismType.Ptr:
					if (++state.DnsLookupCount > 10)
						return SpfQualifier.PermError;

					DnsResolveResult<PtrRecord> dnsPtrResult = await ResolveDnsAsync<PtrRecord>(ip.GetReverseLookupDomain(), RecordType.Ptr, token);
					if ((dnsPtrResult == null) || ((dnsPtrResult.ReturnCode != ReturnCode.NoError) && (dnsPtrResult.ReturnCode != ReturnCode.NxDomain)))
						return SpfQualifier.TempError;

					DomainName ptrMechanismDomain = String.IsNullOrEmpty(mechanism.Domain) ? domain : await ExpandDomainAsync(mechanism.Domain, ip, domain, sender, token);

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

						bool? isPtrMatch = await IsIpMatchAsync(ptrRecord.PointerDomainName, ip, 0, 0, token);
						if (isPtrMatch.HasValue && isPtrMatch.Value)
						{
							if (ptrRecord.PointerDomainName.Equals(ptrMechanismDomain) || (ptrRecord.PointerDomainName.IsSubDomainOf(ptrMechanismDomain)))
								return mechanism.Qualifier;
						}
					}
					break;

				case SpfMechanismType.Exists:
					if (++state.DnsLookupCount > 10)
						return SpfQualifier.PermError;

					if (String.IsNullOrEmpty(mechanism.Domain))
						return SpfQualifier.PermError;

					DomainName existsMechanismDomain = String.IsNullOrEmpty(mechanism.Domain) ? domain : await ExpandDomainAsync(mechanism.Domain, ip, domain, sender, token);

					DnsResolveResult<ARecord> dnsAResult = await ResolveDnsAsync<ARecord>(existsMechanismDomain, RecordType.A, token);
					if ((dnsAResult == null) || ((dnsAResult.ReturnCode != ReturnCode.NoError) && (dnsAResult.ReturnCode != ReturnCode.NxDomain)))
						return SpfQualifier.TempError;

					if (dnsAResult.Records.Count(record => (record.RecordType == RecordType.A)) > 0)
					{
						return mechanism.Qualifier;
					}
					break;

				case SpfMechanismType.Include:
					if (++state.DnsLookupCount > 10)
						return SpfQualifier.PermError;

					if (String.IsNullOrEmpty(mechanism.Domain))
						return SpfQualifier.PermError;

					DomainName includeMechanismDomain = String.IsNullOrEmpty(mechanism.Domain) ? domain : await ExpandDomainAsync(mechanism.Domain, ip, domain, sender, token);

					if (includeMechanismDomain.Equals(domain))
						return SpfQualifier.PermError;

					var includeResult = await CheckHostInternalAsync(ip, includeMechanismDomain, sender, false, state, token);
					switch (includeResult.Result)
					{
						case SpfQualifier.Preplaced:
							return mechanism.Qualifier;

						case SpfQualifier.Fail:
						case SpfQualifier.SoftFail:
						case SpfQualifier.Neutral:
							return SpfQualifier.None;

						case SpfQualifier.TempError:
							return SpfQualifier.TempError;

						case SpfQualifier.PermError:
						case SpfQualifier.None:
							return SpfQualifier.PermError;
					}
					break;

				default:
					return SpfQualifier.PermError;
			}

			return SpfQualifier.None;
		}

19 View Source File : ProxyClient.cs
License : Apache License 2.0
Project Creator : AlexWan

private bool DataIsValid(string ip, string port, string token)
        {
            if (!IPAddress.TryParse(ip, out _))
            {
                return false;
            }

            if (!Int32.TryParse(port, out _))
            {
                return false;
            }

            if (string.IsNullOrEmpty(token))
            {
                return false;
            }
            
            return true;
        }

19 View Source File : GeneratorTests.cs
License : MIT License
Project Creator : alfa-laboratory

[Fact]
        public void TryValidIp()
        {
            var ip = generator.Ip();
            var isValid = IPAddress.TryParse(ip, out _);
            isValid.Should().BeTrue();
        }

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

public static bool TryDecode(byte[] data, out AnnounceResponseMessage message)
        {
            BEncodedValue value;
            string faliureReason = null;
            TimeSpan interval = TimeSpan.Zero;
            int complete = -1;
            int incomplete = -1;
            string peerId = null;
            string peerIp = null;
            int peerPort = -1;
            IDictionary<string, IPEndPoint> peers = new Dictionary<string, IPEndPoint>();
            IPAddress tmpIpAddress;
            IPEndPoint endpoint;
            BEncodedString failureReasonKey = new BEncodedString("failure reason");
            BEncodedString intervalKey = new BEncodedString("interval");
            BEncodedString completeKey = new BEncodedString("complete");
            BEncodedString incompleteKey = new BEncodedString("incomplete");
            BEncodedString peersKey = new BEncodedString("peers");
            BEncodedString peerIdKey = new BEncodedString("peer id");
            BEncodedString ipaddressKey = new BEncodedString("ip");
            BEncodedString portKey = new BEncodedString("port");

            message = null;

            if (data.IsNotNullOrEmpty())
            {
                value = BEncodedValue.Decode(data);

                if (value is BEncodedDictionary)
                {
                    if (value.As<BEncodedDictionary>().ContainsKey(failureReasonKey) &&
                        value.As<BEncodedDictionary>()[failureReasonKey] is BEncodedString)
                    {
                        faliureReason = value.As<BEncodedDictionary>()[failureReasonKey].As<BEncodedString>().Text;
                    }

                    if (value.As<BEncodedDictionary>().ContainsKey(intervalKey) &&
                        value.As<BEncodedDictionary>()[intervalKey] is BEncodedNumber)
                    {
                        interval = TimeSpan.FromSeconds(value.As<BEncodedDictionary>()[intervalKey].As<BEncodedNumber>().Number);
                    }
                    else
                    {
                        return false;
                    }

                    if (value.As<BEncodedDictionary>().ContainsKey(completeKey) &&
                        value.As<BEncodedDictionary>()[completeKey] is BEncodedNumber)
                    {
                        complete = (int)value.As<BEncodedDictionary>()[completeKey].As<BEncodedNumber>().Number;
                    }
                    else
                    {
                        return false;
                    }

                    if (value.As<BEncodedDictionary>().ContainsKey(incompleteKey) &&
                        value.As<BEncodedDictionary>()[incompleteKey] is BEncodedNumber)
                    {
                        incomplete = (int)value.As<BEncodedDictionary>()[incompleteKey].As<BEncodedNumber>().Number;
                    }
                    else
                    {
                        return false;
                    }

                    if (value.As<BEncodedDictionary>().ContainsKey(peersKey) &&
                        value.As<BEncodedDictionary>()[peersKey] is BEncodedList)
                    {
                        foreach (var item in value.As<BEncodedDictionary>()[peersKey].As<BEncodedList>())
                        {
                            if (item is BEncodedDictionary)
                            {
                                if (item.As<BEncodedDictionary>().ContainsKey(peerIdKey) &&
                                    item.As<BEncodedDictionary>()[peerIdKey] is BEncodedString &&
                                    item.As<BEncodedDictionary>().ContainsKey(ipaddressKey) &&
                                    item.As<BEncodedDictionary>()[ipaddressKey] is BEncodedString &&
                                    item.As<BEncodedDictionary>().ContainsKey(portKey) &&
                                    item.As<BEncodedDictionary>()[portKey] is BEncodedNumber)
                                {
                                    peerId = Message.ToPeerId(Encoding.ASCII.GetBytes(item.As<BEncodedDictionary>()[peerIdKey].As<BEncodedString>().Text));
                                    peerIp = item.As<BEncodedDictionary>()[ipaddressKey].As<BEncodedString>().Text;
                                    peerPort = (int)item.As<BEncodedDictionary>()[portKey].As<BEncodedNumber>().Number;

                                    if (IPAddress.TryParse(peerIp, out tmpIpAddress) &&
                                        peerPort >= IPEndPoint.MinPort &&
                                        peerPort <= IPEndPoint.MaxPort)
                                    {
                                        endpoint = new IPEndPoint(tmpIpAddress, (ushort)peerPort);

                                        if (!peers.ContainsKey(endpoint.ToString()))
                                        {
                                            peers.Add(endpoint.ToString(), endpoint);
                                        }
                                    }
                                }
                            }
                            else
                            {
                                var data2 = item.Encode();

                                for (int i = 0; i < data2.Length; i += 6)
                                {
                                    endpoint = new IPEndPoint(new IPAddress(IPAddress.NetworkToHostOrder(BitConverter.ToInt32(data2, i))), IPAddress.NetworkToHostOrder(BitConverter.ToInt16(data2, i + 4)));

                                    if (!peers.ContainsKey(endpoint.ToString()))
                                    {
                                        peers.Add(endpoint.ToString(), endpoint);
                                    }
                                }
                            }
                        }
                    }
                    else
                    {
                        return false;
                    }
                }

                message = new AnnounceResponseMessage(faliureReason, interval, complete, incomplete, peers.Values);

                return true;
            }

            return false;
        }

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

public static string GetCityCode(string Hostname)
        {
            if (Hostname.Contains(":"))
                Hostname = Hostname.Split(':')[0];

            string Country;
            try
            {
                var databaseReader = new DatabaseReader("bin\\GeoLite2-Country.mmdb");

                if (IPAddress.TryParse(Hostname, out _))
                {
                    Country = databaseReader.Country(Hostname).Country.IsoCode;
                }
                else
                {
                    var DnsResult = DNS.Lookup(Hostname);

                    if (DnsResult != null)
                        Country = databaseReader.Country(DnsResult).Country.IsoCode;
                    else
                        Country = "Unknown";
                }
            }
            catch (Exception)
            {
                Country = "Unknown";
            }

            return Country == null ? "Unknown" : Country;
        }

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

private void AddButton_Click(object sender, EventArgs e)
        {
            if (!string.IsNullOrEmpty(IPTextBox.Text))
            {
                if (IPAddress.TryParse(IPTextBox.Text, out var address))
                {
                    IPListBox.Items.Add(string.Format("{0}/{1}", address, PrefixComboBox.SelectedItem));
                }
                else
                {
                    MessageBoxX.Show(i18N.Translate("Please enter a correct IP address"));
                }
            }
            else
            {
                MessageBoxX.Show(i18N.Translate("Please enter an IP"));
            }
        }

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

public static bool TrySplit(string value, out IEnumerable<string> result, ushort maxCount = 0)
        {
            result = Split(value).ToArray();

            return maxCount == 0 || result.Count() <= maxCount
                &&
                result.All(ip => IPAddress.TryParse(ip, out _));
        }

19 View Source File : ModbusClient.cs
License : MIT License
Project Creator : AndreasAmMueller

private IPAddress ResolveHost(string host)
		{
			if (IPAddress.TryParse(host, out var address))
				return address;

			return Dns.GetHostAddresses(host)
				.OrderBy(ip => ip.AddressFamily)
				.Where(ip => ip.AddressFamily == AddressFamily.InterNetwork || ip.AddressFamily == AddressFamily.InterNetworkV6)
				.FirstOrDefault() ?? throw new ArgumentException(nameof(Host), "Host could not be resolved.");
		}

19 View Source File : HttpServer.cs
License : GNU General Public License v3.0
Project Creator : andyvorld

public static async Task ServerLoop(MainWindowViewModel viewmodel)
        {
            Debug.WriteLine("\nHttp Server starting");

            IPAddress ipAddress;
            if (!IPAddress.TryParse(_tcpAddr, out ipAddress))
            {
                try
                {
                    IPHostEntry host = Dns.GetHostEntry(_tcpAddr);
                    ipAddress = host.AddressList[0];
                }
                catch (SocketException)
                {
                    Debug.WriteLine("Invalid hostname, defaulting to loopback");
                    ipAddress = IPAddress.Loopback;
                }
                
            }

            IPEndPoint localEndPoint = new IPEndPoint(ipAddress, _tcpPort);
  
            Socket listener = new Socket(ipAddress.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
            listener.Bind(localEndPoint);
            listener.Listen(10);

            Debug.WriteLine($"Http Server listening on {localEndPoint}\n");

            while (true)
            {
                using (Socket client = listener.Accept())
                {
                    var bytes = new byte[1024];
                    var bytesRec = client.Receive(bytes);

                    string httpRequest = Encoding.ASCII.GetString(bytes, 0, bytesRec);

                    var matches = Regex.Match(httpRequest, @"GET (.+?) HTTP\/[0-9\.]+");
                    if (matches.Groups.Count > 0)
                    {
                        int statusCode = 200;
                        string contentType = "text";
                        string content;

                        string[] request = matches.Groups[1].ToString().Split(new string[] {"/"}, StringSplitOptions.RemoveEmptyEntries);
                        switch ((request.Length) > 0 ? request[0] : "")
                        {
                            case ("devices"):
                                contentType = "text/html";
                                content = "<html>";

                                foreach (var logiDevice in viewmodel.LogiDevices)
                                {
                                    content += $"{logiDevice.DeviceName} : <a href=\"/device/{logiDevice.UsbSerialId}\">{logiDevice.UsbSerialId}</a><br>";
                                }

                                content += "</html>";
                                break;
                            case ("device"):
                                if (request.Length < 2)
                                {
                                    statusCode = 400;
                                    content = "Missing device id";
                                }
                                else
                                {
                                    LogiDevice targetDevice =
                                        viewmodel.LogiDevices.FirstOrDefault(x => x.UsbSerialId == request[1]);

                                    if (targetDevice == null)
                                    {
                                        statusCode = 400;
                                        content = $"Device not found, ID = {request[1]}";
                                    }
                                    else
                                    {
                                        contentType = "text/xml";
                                        await targetDevice.UpdateBatteryPercentage();
                                        content = targetDevice.XmlData();
                                    }
                                }

                                break;
                            default:
                                statusCode = 400;
                                content = $"Requested {matches.Groups[1]}";
                                break;
                        }

                        string response = $"HTTP/1.1 {statusCode}\r\n";
                        response += $"Content-Type: {contentType}\r\n";
                        response += $"Access-Control-Allow-Origin: *\r\n";
                        response += "Cache-Control: no-store, must-revalidate\r\n";
                        response += "Pragma: no-cache\r\n";
                        response += "Expires: 0\r\n";

                        response += $"\r\n{content}";

                        client.Send(Encoding.ASCII.GetBytes(response));
                    }
                }
            }
            // ReSharper disable once FunctionNeverReturns
        }

19 View Source File : Tunnel.cs
License : MIT License
Project Creator : angelobreuer

public async Task StartAsync(int connections = 10)
        {
            // perform DNS resolution once
            if (!IPAddress.TryParse(Information.Url.Host, out var ipAddress))
            {
                var ipHostEntry = await Dns.GetHostEntryAsync(Information.Url.DnsSafeHost);

                ipAddress = ipHostEntry.AddressList.FirstOrDefault()
                    ?? throw new Exception(string.Format(Resources.DnsResolutionFailed, Information.Url.DnsSafeHost));
            }

            var endPoint = new IPEndPoint(ipAddress, Information.Port);

            for (var index = 0; index < Math.Min(connections, Information.MaximumConnections); index++)
            {
                _socketContexts[index] = new TunnelSocketContext(this, endPoint, $"SocketContext-" + index);
                _socketContexts[index].BeginConnect();
            }
        }

19 View Source File : NetworkLoggerConfigurationExtensions.cs
License : Apache License 2.0
Project Creator : anjoy8

private static IPAddress ResolveAddress(string uri)
        {
            // Check if it is IP address
            IPAddress address;

            if (IPAddress.TryParse(uri, out address))
                return address;

            address = ResolveIP(uri);
            if (address != null)
                return address;

            SelfLog.WriteLine("Unable to determine the destination IP-Address");
            return IPAddress.Loopback;
        }

19 View Source File : ModbusUtils.cs
License : GNU Lesser General Public License v3.0
Project Creator : Apollo3zehn

public static bool TryParseEndpoint(ReadOnlySpan<char> value, out IPEndPoint result)
        {
            var addressLength = value.Length;
            var lastColonPos = value.LastIndexOf(':');

            if (lastColonPos > 0)
            {
                if (value[lastColonPos - 1] == ']')
                    addressLength = lastColonPos;

                else if (value.Slice(0, lastColonPos).LastIndexOf(':') == -1)
                    addressLength = lastColonPos;
            }

            if (IPAddress.TryParse(value.Slice(0, addressLength).ToString(), out var address))
            {
                var port = 0U;

                if (addressLength == value.Length ||
                    (uint.TryParse(value.Slice(addressLength + 1).ToString(), NumberStyles.None, CultureInfo.InvariantCulture, out port) && port <= 65536))

                {
                    result = new IPEndPoint(address, (int)port);
                    return true;
                }
            }

            result = null;

            return false;
        }

19 View Source File : SetupForm.cs
License : GNU General Public License v3.0
Project Creator : ASCOMInitiative

public bool ValidIPAddress(string ipAddress, out string errorMessage)
        {
            if (string.IsNullOrEmpty(ipAddress.Trim()))
            {
                errorMessage = "The IP field has no content";
                return false;
            }

            if (ipAddress.ToLower() == SharedConstants.LOCALHOST_NAME_IPV4)
            {
                errorMessage = "";
                return true;
            }

            if (ipAddress == SharedConstants.BIND_TO_ALL_INTERFACES_DESCRIPTION)
            {
                errorMessage = "";
                return true;
            }

            if (ipAddress == SharedConstants.BIND_TO_ALL_INTERFACES_IP_ADDRESS_WEAK)
            {
                errorMessage = "";
                return true;
            }

            if (ipAddress == SharedConstants.BIND_TO_ALL_INTERFACES_IP_ADDRESS_STRONG)
            {
                errorMessage = "";
                return true;
            }

            bool isValidIpAddress = IPAddress.TryParse(ipAddress, out _); // Try and parse the IP address discarding the output (out _)
            if (isValidIpAddress)
            {
                errorMessage = "";
                return true;
            }
            else
            {
                errorMessage = "Address given is not a valid IP address.";
                return false;
            }
        }

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

public IEnumerable _Run()
			{
				string url;
				switch (_config)
				{
					case ADDRESS_AUTO_V4:
						url = ADDRESS_AUTO_V4_URL;
						break;

					case ADDRESS_AUTO_V6:
						url = ADDRESS_AUTO_V6_URL;
						break;

					default:
						Result = IPAddress.TryParse(_config, out _)
							? new KeyValuePair<bool, string>(true, _config)
							: new KeyValuePair<bool, string>(false, "manual; Invalid IP address in config.");
						yield break;
				}

				var request = UnityWebRequest.Get(url);
				yield return request.Send();

				if (request.isError)
				{
					Result = new KeyValuePair<bool, string>(false, "automatic; " + request.error);
					yield break;
				}

				Result = new KeyValuePair<bool, string>(true, request.downloadHandler.text.Trim());
			}

19 View Source File : IpAddressToStringConverter.cs
License : The Unlicense
Project Creator : astenlund

public object? ConvertBack(object? value, Type targetType, object parameter, CultureInfo culture)
        {
            if (value == null)
                return null;

            if (!(value is string str))
                return Binding.DoNothing;

            if (str == "")
                return null;

            if (!_regex.IsMatch(str))
                return Binding.DoNothing;

            return IPAddress.TryParse(str, out var result)
                ? result
                : Binding.DoNothing;
        }

19 View Source File : GrpcNetRemote.cs
License : Apache License 2.0
Project Creator : asynkron

public Task StartAsync()
        {
            lock (_lock)
            {
                if (Started)
                    return Task.CompletedTask;

                var channelProvider = new GrpcNetChannelProvider(_config);
                _endpointManager = new EndpointManager(System, Config, channelProvider);
                _endpointReader = new EndpointReader(System, _endpointManager, Config.Serialization);
                _healthCheck = new HealthServiceImpl();

                if (!IPAddress.TryParse(Config.Host, out var ipAddress))
                    ipAddress = IPAddress.Any;
                IServerAddressesFeature? serverAddressesFeature = null;

                _host = new WebHostBuilder()
                    .UseKestrel()
                    .ConfigureKestrel(serverOptions => {
                            if (_config.ConfigureKestrel == null)
                            {
                                serverOptions.Listen(ipAddress, Config.Port,
                                    listenOptions => listenOptions.Protocols = HttpProtocols.Http2
                                );
                            }
                            else
                            {
                                serverOptions.Listen(ipAddress, Config.Port,
                                    listenOptions => _config.ConfigureKestrel(listenOptions)
                                );
                            }
                        }
                    )
                    .ConfigureServices(serviceCollection => {
                            serviceCollection.AddSingleton(Log.GetLoggerFactory());
                            serviceCollection.AddGrpc(options => {
                                    options.MaxReceiveMessageSize = null;
                                    options.EnableDetailedErrors = true;
                                }
                            );
                            serviceCollection.AddSingleton<Remoting.RemotingBase>(_endpointReader);
                            serviceCollection.AddSingleton<Health.HealthBase>(_healthCheck);
                            serviceCollection.AddSingleton<IRemote>(this);
                        }
                    ).Configure(app => {
                            app.UseRouting();
                            app.UseEndpoints(endpoints => {
                                    endpoints.MapGrpcService<Remoting.RemotingBase>();
                                    endpoints.MapGrpcService<Health.HealthBase>();
                                }
                            );

                            serverAddressesFeature = app.ServerFeatures.Get<IServerAddressesFeature>();
                        }
                    )
                    .Start();
                var uri = serverAddressesFeature!.Addresses.Select(address => new Uri(address)).First();
                var boundPort = uri.Port;
                System.SetAddress(Config.AdvertisedHost ?? Config.Host,
                    Config.AdvertisedPort ?? boundPort
                );
                _endpointManager.Start();
                _logger.LogInformation("Starting Proto.Actor server on {Host}:{Port} ({Address})", Config.Host, Config.Port, System.Address);
                Started = true;
                return Task.CompletedTask;
            }
        }

19 View Source File : LunchUI.cs
License : Apache License 2.0
Project Creator : autowarefoundation

void Start()
        {
            connectStatus = ConnectStatus.None;
            TestConfig.LoadAllData();
            SetModeGroup();
            LoadUrl();
            PanelURL.SetActive(!ROS_Config.ROS2);
            btn_testConnect.onClick.AddListener(() => { TestConnect(); });
            inputField_RosMasterIP?.onEndEdit.AddListener((string value) =>
            {
                if (Uri.TryCreate(value, UriKind.Absolute, out uriRos))
                {
                    text_noticeRosIP.text = "OK";
                    text_noticeRosIP.color = Color.green;
                    SetIPConfig();
                }
                else
                {
                    text_noticeRosIP.text = "Address is not legitimate";
                    text_noticeRosIP.color = Color.red;
                }
            });
            inputField_Port?.onEndEdit.AddListener((string value) =>
            {
                if (int.TryParse(value, out int porttemp) && porttemp < 65536 && porttemp > 0)
                {
                    port = porttemp;
                    text_noticePort.text = "ok";
                    text_noticePort.color = Color.green;
                    SetIPConfig();
                }
                else
                {
                    text_noticePort.text = "port is not legitimate";
                    text_noticePort.color = Color.red;
                }
            });
            inputField_rosIP?.onEndEdit.AddListener((string value) =>
            {
                string[] values = value.Split('.');
                if (values.Length == 4)
                {
                    if (IPAddress.TryParse(value, out IPAddress iPAddress))
                    {
                        if (iPAddress.AddressFamily == AddressFamily.InterNetwork)
                        {
                            iPAddressLocal = iPAddress;
                            text_noticeLocalIP.text = "OK";
                            text_noticeLocalIP.color = Color.green;
                            SetIPConfig();
                            return;
                        }
                    }
                }
                text_noticeLocalIP.text = "Address is not legitimate";
                text_noticeLocalIP.color = Color.red;
            });
        }

19 View Source File : IPEndPointExtension.cs
License : Apache License 2.0
Project Creator : aws

public static bool TryParse(string input, out IPEndPoint endPoint)
        {
            endPoint = null;

            string[] ep = input.Split(':');
            if (ep.Length != 2)
            {
                _logger.InfoFormat("Failed to parse IPEndpoint because input has not exactly two parts splitting by ':'. ({0})", input);
                return false;
            }

            // Validate IP address is in valid range
            IPAddress ip;
            if (!IPAddress.TryParse(ep[0], out ip))
            {
                _logger.InfoFormat("Failed to parse IPEndPoint because ip address is invalid. ({0})", input);
                return false;
            }

            int port;
            if (!int.TryParse(ep[1], NumberStyles.Integer, NumberFormatInfo.InvariantInfo, out port))
            {
                _logger.InfoFormat("Failed to parse IPEndPoint because port is invalid. ({0})", input);
                return false;
            }

            try
            {
                // Validate port number is in valid range
                endPoint = new IPEndPoint(ip, port);
                return true;
            }
            catch (ArgumentOutOfRangeException e)
            {
                _logger.Error(e, "Failed to parse IPEndPoint because argument to IPEndPoint is invalid. ({0}", input);
                return false;
            }
        }

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

public static IPEndPoint ToIPEndPoint(this string epoint, int dfltPort = 0)
    {
      if (string.IsNullOrWhiteSpace(epoint)) throw new AzosException(string.Format(StringConsts.INVALID_EPOINT_ERROR, CoreConsts.NULL_STRING, "null arg"));

      try
      {
        string[] parts = epoint.Split(':');
        var port = parts.Length > 1 && !parts[1].IsNullOrEmpty() ? int.Parse(parts[1]) : dfltPort;

        // Note that the GetHostEntry("127.0.0.1") call looks up the host entry that
        // may not contain localhost, even though it does do IPAddress.TryParse(epoint) call,
        // So we have no other way but to TryParse it outselves.
        IPAddress address;
        if (parts[0] == "*")
          return new IPEndPoint(IPAddress.Any, port);
        else if (IPAddress.TryParse(parts[0], out address))
          return new IPEndPoint(address, port);

        var hostEntry = Dns.GetHostEntry(parts[0]);

        return new IPEndPoint(hostEntry.AddressList.First(a => a.AddressFamily == AddressFamily.InterNetwork), port);
      }
      catch (Exception error)
      {
        throw new AzosException(string.Format(StringConsts.INVALID_EPOINT_ERROR, epoint, error.ToMessageWithType()), error);
      }
    }

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

protected override void DoFilterWork(WorkContext work, IList<WorkFilter> filters, int thisFilterIndex)
    {
      var ipep  = work.m_EffectiveCallerIPEndPoint;

      if (ipep==null)
      {
        var hip = RealIpHdr;
        var hprt = RealPortHdr;

        hip = hip.IsNotNullOrWhiteSpace() ? hip : "Real-IP";
        hprt  = hprt.IsNotNullOrWhiteSpace() ? hprt : "Real-Port";


        var rIP = work.Request.Headers[hip];
        var rPort = work.Request.Headers[hprt];

        if (hip.EqualsOrdIgnoreCase(WebConsts.HTTP_HDR_X_FORWARDED_FOR) && rIP.IsNotNullOrWhiteSpace())
        {
          var ic = rIP.LastIndexOf(',');
          if (ic>0 && ic < rIP.Length-1)
          {
            rIP = rIP.Substring(ic + 1);//take the last IP address in the header list to prevent spoofing
            // see: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/X-Forwarded-For
          }
        }

        if (rIP.IsNotNullOrWhiteSpace())
        {
          IPAddress address = null;
          if (IPAddress.TryParse(rIP, out address))
          {
            work.m_EffectiveCallerIPEndPoint = new IPEndPoint(address, rPort.AsInt(0));
          }
        }
      }

      this.InvokeNextWorker(work, filters, thisFilterIndex);
    }

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

protected override void DoFilterWork(WorkContext work, IList<WorkFilter> filters, int thisFilterIndex)
      {
        var needLookup = true;
        var address = work.EffectiveCallerIPEndPoint.Address;

        if (work.GeoEnreplacedy!=null)
         needLookup = !string.Equals(work.GeoEnreplacedy.Query, address);


        if (needLookup && m_LookupMatches.Count>0)
        {
          foreach(var match in m_LookupMatches.OrderedValues)
          {
            var matched = match.Make(work);
            needLookup = matched!=null;

            if (needLookup)
            {
              var useAddr = matched[VAR_USE_ADDR];
              if (useAddr!=null)
              {
                IPAddress ip;
                if (IPAddress.TryParse(useAddr.ToString(), out ip))
                  address = ip;
              }
              break;
            }
          }
        }

        if (needLookup)
        {
          var svc = App.ModuleRoot.Get<GeoLookupModule>(GeoLookupModuleName);//throws if module not found
          var lookedUp = svc.Lookup(address);
          work.GeoEnreplacedy = lookedUp;

          if (Server.m_InstrumentationEnabled)
          {
            Interlocked.Increment(ref Server.m_stat_GeoLookup);
            if (lookedUp!=null)
               Interlocked.Increment(ref Server.m_stat_GeoLookupHit);
          }
        }

        this.InvokeNextWorker(work, filters, thisFilterIndex);
      }

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

public async Task HandleConnectionAsync(HybridConnectionStream hybridConnectionStream)
        {
            UdpClient client = null;

            if (config.BindAddress != null)
            {
                var computerProperties = IPGlobalProperties.GetIPGlobalProperties();
                var unicastAddresses = computerProperties.GetUnicastAddresses();
                IList<IPAddress> ipAddresses = null;

                ipAddresses = IPAddress.TryParse(config.BindAddress, out var ipAddress)
                    ? new[] { ipAddress }
                    : Dns.GetHostEntry(config.BindAddress).AddressList;

                List<IPAddress> eligibleAddresses = new List<IPAddress>();
                eligibleAddresses.AddRange(from hostAddress in ipAddresses
                    where IPAddress.IsLoopback(hostAddress)
                    select hostAddress);
                eligibleAddresses.AddRange(from unicastAddress in unicastAddresses
                    join hostAddress in ipAddresses on unicastAddress.Address equals hostAddress
                    where !IPAddress.IsLoopback(hostAddress)
                    select hostAddress);

                // pick one of those eligible endpoints
                client = new UdpClient(new IPEndPoint(eligibleAddresses[rnd.Next(eligibleAddresses.Count)], 0));
            }
            else
            {
                client = new UdpClient();
            }

            using (client)
            {
                client.Connect(targetServer, targetPort);

                CancellationTokenSource socketAbort = new CancellationTokenSource(maxIdleTime);
                await Task.WhenAll(
                    Send(hybridConnectionStream, client, socketAbort)
                        .ContinueWith((t) => socketAbort.Cancel(), TaskContinuationOptions.OnlyOnFaulted),
                    Receive(hybridConnectionStream, client, socketAbort)
                        .ContinueWith((t) => socketAbort.Cancel(), TaskContinuationOptions.OnlyOnFaulted));
            }
        }

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

void StartEndpoint(LocalForward localForward, LocalForwardBinding binding)
        {
            var startActivity = BridgeEventSource.NewActivity("LocalForwardBridgeStart", activity);
            Uri hybridConnectionUri = null;
            
            BridgeEventSource.Log.LocalForwardBridgeStarting(startActivity, localForward);

            var rcbs = localForward.RelayConnectionStringBuilder ?? new RelayConnectionStringBuilder(config.AzureRelayConnectionString);
            rcbs.EnreplacedyPath = localForward.RelayName;
            hybridConnectionUri = new Uri(rcbs.Endpoint, rcbs.EnreplacedyPath);

#if !NETFRAMEWORK
            if (!string.IsNullOrEmpty(binding.BindLocalSocket))
            {
                if (Environment.OSVersion.Platform == PlatformID.Win32NT)
                {
                    BridgeEventSource.Log.ThrowingException(
                        new NotSupportedException("Unix sockets are not supported on Windows"));
                }

                SocketLocalForwardBridge socketListenerBridge = null;

                try
                {
                    {
                        socketListenerBridge = SocketLocalForwardBridge.FromConnectionString(this.config, rcbs, binding.PortName);
                        socketListenerBridge.Run(binding.BindLocalSocket);

                        this.socketListenerBridges.Add(hybridConnectionUri.AbsoluteUri, socketListenerBridge);
                    }
                    BridgeEventSource.Log.LocalForwardBridgeStart(startActivity, IPAddress.Any, localForward);
                }
                catch (Exception e)
                {
                    BridgeEventSource.Log.LocalForwardBridgeStartFailure(startActivity, localForward, e);
                    if (!config.ExitOnForwardFailure.HasValue ||
                         config.ExitOnForwardFailure.Value)
                    {
                        throw;
                    }
                }
                return;
            }
#endif

            if (binding.BindPort > 0)
            {
                TcpLocalForwardBridge tcpListenerBridge = null;
                try
                {
                    IPHostEntry localHostEntry = Dns.GetHostEntry(Dns.GetHostName());

                    // Resolve the host name. Whether this is in the hosts file or in some 
                    // form of DNS server shouldn't matter for us here (means we do not touch 
                    // the hosts file in this process), but the address MUST resolve to a local 
                    // endpoint or to a loopback endpoint

                    IPAddress bindToAddress;
                    Random rnd = new Random();
                    if (!IPAddress.TryParse(binding.BindAddress, out bindToAddress))
                    {
                        IPHostEntry hostEntry = Dns.GetHostEntry(binding.BindAddress);
                        bindToAddress = hostEntry.AddressList[rnd.Next(hostEntry.AddressList.Length)];
                    }

                    if (bindToAddress != null)
                    {
                        tcpListenerBridge =
                            TcpLocalForwardBridge.FromConnectionString(this.config, rcbs, binding.PortName);
                        tcpListenerBridge.Run(new IPEndPoint(bindToAddress, binding.BindPort));

                        this.listenerBridges.Add(hybridConnectionUri.AbsoluteUri, tcpListenerBridge);
                    }

                    BridgeEventSource.Log.LocalForwardBridgeStart(startActivity, bindToAddress, localForward);
                }
                catch (Exception e)
                {
                    BridgeEventSource.Log.LocalForwardBridgeStartFailure(startActivity, localForward, e);
                    if (!config.ExitOnForwardFailure.HasValue ||
                        config.ExitOnForwardFailure.Value)
                    {
                        throw;
                    }
                }
            }
            else  if ( binding.BindPort < 0 )
            {
                UdpLocalForwardBridge udpListenerBridge = null;
                try
                {
                    IPHostEntry localHostEntry = Dns.GetHostEntry(Dns.GetHostName());

                    // Resolve the host name. Whether this is in the hosts file or in some 
                    // form of DNS server shouldn't matter for us here (means we do not touch 
                    // the hosts file in this process), but the address MUST resolve to a local 
                    // endpoint or to a loopback endpoint

                    IPAddress bindToAddress;
                    Random rnd = new Random();
                    if (!IPAddress.TryParse(binding.BindAddress, out bindToAddress))
                    {
                        IPHostEntry hostEntry = Dns.GetHostEntry(binding.BindAddress);
                        bindToAddress = hostEntry.AddressList[rnd.Next(hostEntry.AddressList.Length)];
                    }

                    if (bindToAddress != null)
                    {
                        udpListenerBridge =
                            UdpLocalForwardBridge.FromConnectionString(this.config, rcbs, binding.PortName);
                        udpListenerBridge.Run(new IPEndPoint(bindToAddress, -binding.BindPort));

                        this.udpBridges.Add(hybridConnectionUri.AbsoluteUri, udpListenerBridge);
                    }

                    BridgeEventSource.Log.LocalForwardBridgeStart(startActivity, bindToAddress, localForward);
                }
                catch (Exception e)
                {
                    BridgeEventSource.Log.LocalForwardBridgeStartFailure(startActivity, localForward, e);
                    if (!config.ExitOnForwardFailure.HasValue ||
                        config.ExitOnForwardFailure.Value)
                    {
                        throw;
                    }
                }
            }

        }

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

public async Task HandleConnectionAsync(HybridConnectionStream hybridConnectionStream)
        {
            using (TcpClient client = new TcpClient())
            {
                client.NoDelay = true;
                client.SendBufferSize = client.ReceiveBufferSize = 65536;
                client.SendTimeout = 60000;
                if (config.BindAddress != null)
                {
                    var computerProperties = IPGlobalProperties.GetIPGlobalProperties();
                    var unicastAddresses = computerProperties.GetUnicastAddresses();
                    IList<IPAddress> ipAddresses = null;

                    ipAddresses = IPAddress.TryParse(config.BindAddress, out var ipAddress)
                        ? new[] { ipAddress }
                        : Dns.GetHostEntry(config.BindAddress).AddressList;

                    List<IPAddress> eligibleAddresses = new List<IPAddress>();
                    eligibleAddresses.AddRange(from hostAddress in ipAddresses
                                               where IPAddress.IsLoopback(hostAddress)
                                               select hostAddress);
                    eligibleAddresses.AddRange(from unicastAddress in unicastAddresses
                                               join hostAddress in ipAddresses on unicastAddress.Address equals hostAddress
                                               where !IPAddress.IsLoopback(hostAddress)
                                               select hostAddress);
                    // pick one of those eligible endpoints
                    client.Client.Bind(new IPEndPoint(eligibleAddresses[rnd.Next(eligibleAddresses.Count)], 0));
                }
                await client.ConnectAsync(targetServer, targetPort);
                var tcpstream = client.GetStream();

                CancellationTokenSource socketAbort = new CancellationTokenSource();
                await Task.WhenAll(
                    StreamPump.RunAsync(hybridConnectionStream, tcpstream,
                        () => client.Client.Shutdown(SocketShutdown.Send), socketAbort.Token)
                        .ContinueWith((t) => socketAbort.Cancel(), TaskContinuationOptions.OnlyOnFaulted),
                    StreamPump.RunAsync(tcpstream, hybridConnectionStream, () => hybridConnectionStream.Shutdown(), socketAbort.Token))
                        .ContinueWith((t) => socketAbort.Cancel(), TaskContinuationOptions.OnlyOnFaulted);

            }

        }

See More Examples