System.Net.IPAddress.ToString()

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

1323 Examples 7

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 : IpHelper.cs
License : MIT License
Project Creator : Amitpnk

public static string GetIpAddress()
        {
            var host = Dns.GetHostEntry(Dns.GetHostName());
            foreach (var ip in host.AddressList)
            {
                if (ip.AddressFamily == AddressFamily.InterNetwork)
                {
                    return ip.ToString();
                }
            }
            return string.Empty;
        }

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

public override Task<HandShakeReply> CrossChainHandShake(HandShake request, ServerCallContext context)
        {
            Logger.LogDebug($"Received shake from chain {ChainHelper.ConvertChainIdToBase58(request.ChainId)}.");

            if (!GrpcUriHelper.TryParsePrefixedEndpoint(context.Peer, out IPEndPoint peerEndpoint))
                return Task.FromResult(new HandShakeReply
                    {Status = HandShakeReply.Types.HandShakeStatus.InvalidHandshakeRequest});

            _ = PublishCrossChainRequestReceivedEvent(peerEndpoint.Address.ToString(), request.ListeningPort,
                request.ChainId);
            return Task.FromResult(new HandShakeReply {Status = HandShakeReply.Types.HandShakeStatus.Success});
        }

19 View Source File : Daemon.cs
License : MIT License
Project Creator : alexanderdna

public bool AcceptPeerList(IList<(System.Net.IPAddress, int)> peerAddresses)
        {
            ibd.Prepare();

            var clients = new List<Client>();

            for (int i = 0, c = peerAddresses.Count; i < c; ++i)
            {
                var (host, port) = peerAddresses[i];
                var client = new Client(host.ToString(), port, logger);
                client.OnMessageReceived += onMessageReceived;
                bool isConnected = client.Connect();
                if (isConnected)
                {
                    client.StartAsync(cancellationToken);
                    clients.Add(client);
                    logger.Log(App.LogLevel.Info, "Connected to peer " + client.Context.ClientEndPoint);
                }
            }

            if (clients.Count > 0)
            {
                lock (houseKeepingLock)
                {
                    for (int i = 0, c = clients.Count; i < c; ++i)
                    {
                        var ctx = clients[i].Context;
                        if (ibd.HasPeer(ctx) is false)
                        {
                            ibd.AddPeer(ctx);
                            sendVersionMessage(ctx);
                        }
                        peers.Add(ctx);
                    }
                }

                logger.Log(App.LogLevel.Info, $"Connected to {clients.Count} peers.");
                return true;
            }
            else
            {
                ibd.Fail();
                logger.Log(App.LogLevel.Warning, "Cannot connect to any peers.");

                return false;
            }
        }

19 View Source File : ZeroApplication.cs
License : Mozilla Public License 2.0
Project Creator : agebullhu

private static string GetHostIps()
        {
            var ips = new StringBuilder();
            var first = true;
            foreach (var address in Dns.GetHostAddresses(Dns.GetHostName()))
            {
                if (address.IsIPv4MappedToIPv6 || address.IsIPv6LinkLocal || address.IsIPv6Multicast ||
                    address.IsIPv6SiteLocal || address.IsIPv6Teredo)
                    continue;
                var ip = address.ToString();
                if (ip == "127.0.0.1" || ip == "127.0.1.1" || ip == "::1" || ip == "-1")
                    continue;
                if (first)
                    first = false;
                else
                    ips.Append(" , ");
                ips.Append(ip);
            }

            return ips.ToString();
        }

19 View Source File : AppManager.cs
License : MIT License
Project Creator : admaiorastudio

private async Task ConnectAsync()
        {
            if (_isConnected)
                return;

            // Emulators loopback addresses
            IPAddress[] loopbackAddresses = new[]
            {
                IPAddress.Parse("127.0.0.1"),
                IPAddress.Parse("10.0.2.2"),
                IPAddress.Parse("10.0.3.2"),
                IPAddress.Parse("169.254.80.80")
            };

            // Check if we are an emulator instance
            List<Task<string>> waitTasks = new List<Task<string>>();
            CancellationTokenSource cts = new CancellationTokenSource();

            // Look for server using localhost (an emulator device)
            foreach (var ipAddress in loopbackAddresses.Take(1))
            {
                waitTasks.Add(Task.Run<string>(
                    async () =>
                    {
                        try
                        {
                            bool isPortOpen = TryPing(ipAddress.ToString(), 5001, 300);
                            if (!isPortOpen)
                                return null;

                            var connection = new HubConnectionBuilder()
                                .WithUrl($"http://{ipAddress.ToString()}:5001/hub")
                                .Build();

                            await connection.StartAsync(cts.Token);
                            if (cts.IsCancellationRequested)
                                return null;

                            _useLocalHost = true;
                            _hubConnection = connection;

                            cts.Cancel();
                            return ipAddress.ToString();
                        }
                        catch (Exception ex)
                        {
                            return null;
                        }

                    }, cts.Token));
            }

            // Look for server using broadcast (a real device)
            waitTasks.Add(Task.Run<string>(
                async () =>
                {
                    // Discover the server
                    using (UdpClient client = new UdpClient())
                    {
                        client.EnableBroadcast = true;

                        byte[] requestData = Encoding.ASCII.GetBytes($"AreYouTheServer?");
                        Task<int> sendTask = client.SendAsync(requestData, requestData.Length, new IPEndPoint(IPAddress.Broadcast, 5002));
                        await Task.WhenAny(new[] { sendTask, Task.Delay(300) });
                        if (sendTask.IsCompleted)
                        {
                            if (cts.IsCancellationRequested)
                                return null;

                            Task<UdpReceiveResult> receiveTask = client.ReceiveAsync();
                            await Task.WhenAny(new[] { receiveTask, Task.Delay(300) });
                            if (receiveTask.IsCompleted)
                            {
                                if (cts.IsCancellationRequested)
                                    return null;

                                UdpReceiveResult serverResponseData = receiveTask.Result;
                                string serverResponse = Encoding.ASCII.GetString(serverResponseData.Buffer);
                                if (serverResponse == "YesIamTheServer!")
                                {
                                    string ipAddress = serverResponseData.RemoteEndPoint.Address.ToString();
                                    _useLocalHost = false;
                                    _hubConnection = null;

                                    cts.Cancel();
                                    return ipAddress.ToString();

                                }
                            }
                        }

                        client.Close();
                    }

                    return null;
                }));

            // Timeout task 
            waitTasks.Add(Task.Run<string>(
                async () =>
                {
                    try
                    {
                        await Task.Delay(5000, cts.Token);
                        cts.Cancel();
                        return null;
                    }
                    catch
                    {
                        return null;
                    }
                }));

            try
            {
                string ipAddress = await WaitForAnyGetHostIpTaskAsync(waitTasks);
                if (ipAddress != null)
                {
                    if (_hubConnection == null)
                    {
                        string port = _useLocalHost ? "5001" : "5002";
                        _hubConnection = new HubConnectionBuilder()
                            .WithUrl($"http://{ipAddress.ToString()}:{port}/hub")
                            .Build();

                        await _hubConnection.StartAsync();
                    }

                    _isConnected = true;
                    _serverAddress = ipAddress;

                    _hubConnection.Closed +=
                        async (error) =>
                        {
                            System.Diagnostics.Debug.WriteLine("Connection with RealXaml has been lost.");                            

                            while(_hubConnection.State == HubConnectionState.Disconnected)
                            {
                                bool isPortOpen = TryPing(ipAddress.ToString(), 5001, 300);
                                if (isPortOpen)
                                {
                                    System.Diagnostics.Debug.WriteLine("Trying to reconnect again...");
                                    await _hubConnection.StartAsync();
                                    if (_hubConnection.State == HubConnectionState.Connected)
                                    {
                                        await Task.Delay(300);
                                        await _hubConnection.SendAsync("NotifyIde", "Connection was lost. Here I'am again.");

                                        System.Diagnostics.Debug.WriteLine($"Successfully restored lost to the RealXaml server.");
                                        break;
                                    }
                                }

                                System.Diagnostics.Debug.WriteLine("Unable to connect. Retrying in 5secs.");
                                await Task.Delay(5000);
                            }
                        };                    

                    _hubConnection.On<string, byte[], bool>("ReloadXaml", 
                        async (pageId, data, refresh) => await WhenReloadXaml(pageId, data, refresh));

                    _hubConnection.On<string, byte[]>("Reloadreplacedembly", 
                        async (replacedemblyName, data) => await WhenReloadreplacedembly(replacedemblyName, data));

                    string clientId = $"RXID-{DateTime.Now.Ticks}";
                    await _hubConnection.SendAsync("RegisterClient", clientId);

                    System.Diagnostics.Debug.WriteLine($"Successfully connected to the RealXaml server.");
                    System.Diagnostics.Debug.WriteLine($"Your client ID is {clientId}");

                    return;
                }
            }
            catch(Exception ex)
            {
                System.Diagnostics.Debug.WriteLine("Error while trying to connect to the RealXaml server.");
                System.Diagnostics.Debug.WriteLine(ex);
            }       
        }

19 View Source File : ConsulRegistration.cs
License : MIT License
Project Creator : AlphaYu

private static Uri GetServiceAddressInternal(IApplicationBuilder app, ConsulConfig consulOption)
        {
            var errorMsg = string.Empty;
            Uri serviceAddress = default;

            if (consulOption == null)
                throw new Exception("请正确配置Consul");

            if (string.IsNullOrEmpty(consulOption.ConsulUrl))
                throw new Exception("请正确配置ConsulUrl");

            if (string.IsNullOrEmpty(consulOption.ServiceName))
                throw new Exception("请正确配置ServiceName");

            if (string.IsNullOrEmpty(consulOption.HealthCheckUrl))
                throw new Exception("请正确配置HealthCheckUrl");

            if (consulOption.HealthCheckIntervalInSecond <= 0)
                throw new Exception("请正确配置HealthCheckIntervalInSecond");

            //获取网卡所有Ip地址,排除回路地址
            var allIPAddress = System.Net.NetworkInformation.NetworkInterface.GetAllNetworkInterfaces()
                               .Select(p => p.GetIPProperties())
                               .SelectMany(p => p.UnicastAddresses)
                               .Where(p => p.Address.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork && !System.Net.IPAddress.IsLoopback(p.Address))
                               .Select(p => p.Address.ToString()).ToArray();

            //获取web服务器监听地址,也就是提供访问的地址
            var listenAddresses = app.ServerFeatures.Get<IServerAddressesFeature>().Addresses.ToList();
            List<Uri> listenUrls = new List<Uri>();
            listenAddresses.ForEach(a =>
            {
                var address = a.Replace("[::]", "0.0.0.0")
                               .Replace("+", "0.0.0.0")
                               .Replace("*", "0.0.0.0");

                listenUrls.Add(new Uri(address));
            });

            var logger = app.ApplicationServices.GetRequiredService<ILogger<ConsulConfig>>();

            //第一种注册方式,在配置文件中指定服务地址
            //如果配置了服务地址, 只需要检测是否在listenUrls里面即可
            if (!string.IsNullOrEmpty(consulOption.ServiceUrl))
            {
                logger.LogInformation("consulOption.ServiceUrl:{0}", consulOption.ServiceUrl);

                serviceAddress = new Uri(consulOption.ServiceUrl);
                bool isExists = listenUrls.Where(p => p.Host == serviceAddress.Host || p.Host == "0.0.0.0").Any();
                if (isExists)
                    return serviceAddress;
                else
                    throw new Exception($"服务{consulOption.ServiceUrl}配置错误 listenUrls={string.Join(',', (IEnumerable<Uri>)listenUrls)}");
            }

            //第二种注册方式,服务地址通过docker环境变量(DOCKER_LISTEN_HOSTANDPORT)指定。
            //可以写在dockerfile文件中,也可以运行容器时指定。运行容器时指定才是最合理的,大家看各自的情况怎么处理吧。
            var dockerListenServiceUrl = Environment.GetEnvironmentVariable("DOCKER_LISTEN_HOSTANDPORT");
            if (!string.IsNullOrEmpty(dockerListenServiceUrl))
            {
                logger.LogInformation("dockerListenServiceUrl:{0}", dockerListenServiceUrl);
                serviceAddress = new Uri(dockerListenServiceUrl);
                return serviceAddress;
            }

            //第三种注册方式,注册程序自动获取服务地址
            //本机所有可用IP与listenUrls进行匹配, 如果listenUrl是"0.0.0.0"或"[::]", 则任意IP都符合匹配
            var matches = allIPAddress.SelectMany(ip =>
                                      listenUrls
                                      .Where(uri => ip == uri.Host || uri.Host == "0.0.0.0")
                                      .Select(uri => new { Protocol = uri.Scheme, ServiceIP = ip, Port = uri.Port })
                                      ).ToList();

            //过滤无效地址
            var filteredMatches = matches.Where(p => !p.ServiceIP.Contains("0.0.0.0")
                                                && !p.ServiceIP.Contains("localhost")
                                                && !p.ServiceIP.Contains("127.0.0.1")
                                                );

            var finalMatches = filteredMatches.ToList();

            //没有匹配的地址,抛出异常
            if (finalMatches.Count() == 0)
                throw new Exception($"没有匹配的Ip地址=[{string.Join(',', allIPAddress)}], urls={string.Join(',', (IEnumerable<Uri>)listenUrls)}");

            //只有一个匹配,直接返回
            if (finalMatches.Count() == 1)
            {
                serviceAddress = new Uri($"{finalMatches[0].Protocol}://{ finalMatches[0].ServiceIP}:{finalMatches[0].Port}");
                logger.LogInformation("serviceAddress:{0}", serviceAddress);
                return serviceAddress;
            }

            //匹配多个,直接返回第一个
            serviceAddress = new Uri($"{finalMatches[0].Protocol}://{ finalMatches[0].ServiceIP}:{finalMatches[0].Port}");
            logger.LogInformation("serviceAddress-first:{0}", serviceAddress);
            return serviceAddress;
        }

19 View Source File : IOServer.cs
License : MIT License
Project Creator : a11s

internal Task<bool> InitServerAsync(ChannelHandlerAdapter handler, IPEndPoint localipep,Action afterchannel)
        {
            iogroup = new MulreplacedhreadEventLoopGroup();
            //workergroup = new MulreplacedhreadEventLoopGroup();
            try
            {
                if (bootstrap != null)
                {
                    throw new InvalidOperationException("重复init");
                }
                bootstrap = new Bootstrap();
                bootstrap.Group(iogroup)
                    .Channel<SocketDatagramChannel>()
                    .Option(ChannelOption.SoBroadcast, true)
                    .Handler(handler);
                var _channel = bootstrap.BindAsync(localipep);
                //channel = _channel.Result;
                _channel.ContinueWith((c) =>
                {
                    var ch = c.Result;
                    this.Channel = ch;
                    if (ch.LocalAddress is IPEndPoint ipep)
                    {
                        IPAddress[] ipaddrs = Dns.GetHostAddresses(Environment.MachineName);
                        foreach (var ipaddr in ipaddrs)
                        {
                            DebugLog(ipaddr.ToString());
                        }
                    }
                    DebugLog($"inited {ch.LocalAddress}");
                    afterchannel.Invoke();
                });
                return Task.FromResult(true);
            }
            catch (System.Threading.ThreadInterruptedException e)
            {
                DebugLog(e.ToString());
                DebugLog("shutdown");
                iogroup.ShutdownGracefullyAsync();
            }
            return Task.FromResult(false);
        }

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

public static string GetCurrentIp(string preferredNetworks)
        {
            var instanceIp = "127.0.0.1";

            try
            {
                // 获取可用网卡
                var nics = NetworkInterface.GetAllNetworkInterfaces()?.Where(network => network.OperationalStatus == OperationalStatus.Up);

                // 获取所有可用网卡IP信息
                var ipCollection = nics?.Select(x => x.GetIPProperties())?.SelectMany(x => x.UnicastAddresses);

                foreach (var ipadd in ipCollection)
                {
                    if (!IPAddress.IsLoopback(ipadd.Address) && ipadd.Address.AddressFamily == AddressFamily.InterNetwork)
                    {
                        if (string.IsNullOrEmpty(preferredNetworks))
                        {
                            instanceIp = ipadd.Address.ToString();
                            break;
                        }

                        if (!ipadd.Address.ToString().StartsWith(preferredNetworks)) continue;
                        instanceIp = ipadd.Address.ToString();
                        break;
                    }
                }
            }
            catch
            {
                // ignored
            }

            return instanceIp;
        }

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

public string Execute(SocketCommandContext context, string ip, string token)
        {
            try
            {
                IPEndPoint serverAdr;
                var message = CanExecute(context, ip, token, out serverAdr);
                if (!string.IsNullOrEmpty(message))
                {
                    return message;
                }

                try
                {
                    new TcpClient(serverAdr.Address.ToString(), serverAdr.Port);
                }
                catch
                (Exception ex)
                {
                    return Languages.Translator.ErrServerNotAvailable + "\n" + ex.Message;
                }

                var client = new SessionClient();
                if (!client.Connect(serverAdr.Address.ToString(), serverAdr.Port))
                {
                    return Languages.Translator.ErrServerNotAvailable;
                }

                var preplaced = new CryptoProvider().GetHash(token);
                if (!client.Login(SessionClientWrapper.DiscrodLogin, preplaced, null))
                {
                    return Languages.Translator.ErrInvalidToken;
                }

                var channelToServer = new Chanel2Server()
                {
                    Id = context.Channel.Id,
                    IP = serverAdr.Address.ToString(),
                    Port = serverAdr.Port,
                    LinkCreator = context.Message.Author.Id,
                    LastOnlineTime = DateTime.UtcNow.AddDays(-1),
                    Token = token,
                    LastRecivedPostIndex = -1,
                };

                //


                _appContext.RegisterNewServer(channelToServer, new SessionClientWrapper(channelToServer, client));
                context.Message.DeleteAsync();

                return string.Format(Languages.Translator.InfServerReg, serverAdr.ToString(), "#" + context.Channel.Name);
            }
            catch (Exception ex)
            {
                Loger.Log(ex.ToString());
                return "Internal error";
            }
        }

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

public static PacketWriter SetServers(string serverName, ImmutableList<IPEndPoint> serverIps)
    {
        PacketWriter pWriter = PacketWriter.Of(SendOp.SERVER_LIST);

        pWriter.WriteByte(1); // If false packet isn't processed
        pWriter.WriteInt(1); // Unk.
        pWriter.WriteUnicodeString(serverName);
        pWriter.WriteByte(); // Unk.

        pWriter.Write((ushort) serverIps.Count);
        foreach (IPEndPoint endpoint in serverIps)
        {
            pWriter.WriteUnicodeString(endpoint.Address.ToString());
            pWriter.Write((ushort) endpoint.Port);
        }

        pWriter.WriteInt(100); // Unk.

        short nMultiServerChannel = 10; // Doesn't seems to go past 9 channels ingame ??
        pWriter.WriteShort(nMultiServerChannel);
        for (short i = 1; i <= nMultiServerChannel; ++i)
        {
            pWriter.WriteShort(i);
        }

        return pWriter;
    }

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

public bool ValidAccess(System.Net.IPEndPoint endPoint)
		{
			bool permit = true;
			if (IPAddress.IsLoopback(endPoint.Address))
			{
				if (!string.IsNullOrEmpty(PermitUser))
				{
					if (_cache["port_" + endPoint.Port.ToString()] != null)
					{
						permit = true;
					}
					else
					{
						try
						{
							var user = GetConnectedUser(endPoint.Port, endPoint.AddressFamily);
							permit = string.Equals(user, PermitUser, StringComparison.OrdinalIgnoreCase);
							if (permit)
								_cache["port_" + endPoint.Port.ToString()] = string.Empty;
						}
						catch (Exception ex) { TraceLogger.Instance.WriteException(ex); throw; }
					}
				}
			}
			else if (PermitAddress != null)
			{
				permit = (endPoint.Address.ToString() == PermitAddress.ToString());
			}
			return permit;
		}

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

internal override void ParseRecordData(byte[] resultData, int currentPosition, int length)
		{
			int startPosition = currentPosition;

			Precedence = resultData[currentPosition++];
			GatewayType = (IpSecGatewayType) resultData[currentPosition++];
			Algorithm = (IpSecAlgorithm) resultData[currentPosition++];
			switch (GatewayType)
			{
				case IpSecGatewayType.None:
					Gateway = String.Empty;
					break;
				case IpSecGatewayType.IpV4:
					Gateway = new IPAddress(DnsMessageBase.ParseByteData(resultData, ref currentPosition, 4)).ToString();
					break;
				case IpSecGatewayType.IpV6:
					Gateway = new IPAddress(DnsMessageBase.ParseByteData(resultData, ref currentPosition, 16)).ToString();
					break;
				case IpSecGatewayType.Domain:
					Gateway = DnsMessageBase.ParseDomainName(resultData, ref currentPosition).ToString();
					break;
			}
			PublicKey = DnsMessageBase.ParseByteData(resultData, ref currentPosition, length + startPosition - currentPosition);
		}

19 View Source File : Utility.IP.cs
License : MIT License
Project Creator : 7Bytes-Studio

public static string GetPublicIP()
            {
                if (!string.IsNullOrEmpty(g_CachePublicIp))
                {
                    return g_CachePublicIp;
                }

                var hostName = Dns.GetHostName();
                var addresses = Dns.GetHostAddresses(hostName);
                string ip = string.Empty;
                for (int i = 0; i < addresses.Length; i++)
                {
                    if (!string.IsNullOrEmpty(ip = g_IpRegex.Match(addresses[i].ToString()).Groups[0].Value))
                    {
                        return ip.Trim();
                    }
                }
                return string.Empty;
            }

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

protected internal void Listen()
        {
            try
            {
                _tcpListener = new TcpListener(IPAddress.Any, ExitPort);
                _tcpListener.Start();
                Task.Run(Sender);
                Started?.Invoke();

                while (true)
                {
                    TcpClient tcpClient = _tcpListener.AcceptTcpClient();

                    var ip = ((IPEndPoint)tcpClient.Client.RemoteEndPoint).Address.ToString();
                    if (!_permittedIp.Contains(ip))
                    {
                        tcpClient.Close();
                        continue;
                    }
                    
                    AdminPanelClient clientObject = new AdminPanelClient(tcpClient, this);
                    clientObject.Token = PermittedToken;

                    Thread clientThread = new Thread(clientObject.Process);
                    clientThread.Start();
                }
            }
            catch (Exception ex)
            {
                Disconnect();
                Disconnected?.Invoke();
            }
        }

19 View Source File : ViewerServer.cs
License : MIT License
Project Creator : admaiorastudio

public void Start()
        {
            _cts = new CancellationTokenSource();


            Task.Run(() =>
            {
                UdpClient server = new UdpClient(5002);
                byte[] responseData = Encoding.ASCII.GetBytes("YesIamTheServer!");
                while (!_cts.IsCancellationRequested)
                {
                    IPEndPoint clientEp = new IPEndPoint(IPAddress.Any, 0);
                    byte[] clientRequestData = server.Receive(ref clientEp);
                    string clientRequest = Encoding.ASCII.GetString(clientRequestData);

                    if (clientRequest.Contains("AreYouTheServer?"))
                    {                        
                        System.Diagnostics.Debug.WriteLine($"A new peer is connecting @ {clientEp.Address.ToString()}:{clientEp.Port}");
                        server.Send(responseData, responseData.Length, clientEp);
                    }
                }

            }, _cts.Token);
            
            _host = WebHost.CreateDefaultBuilder()
                .UseKestrel()               
                .UseUrls($"http://localhost:5001", $"http://{GetLocalIPAddress()}:5002")
                .UseStartup<Startup>()
                .Build();

            _host.Run();
        }

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

private void SetFip(Mode mode)
        {
            aio_dial((int)NameList.TYPE_CLRFIP, "");
            if (mode.ProcesssIPFillter)
            {
                aio_dial((int)NameList.TYPE_FILTERIP, "true");
            }
            else
            {
                aio_dial((int)NameList.TYPE_FILTERIP, "false");

                if (Global.Settings.STUN_Server == "stun.stunprotocol.org")
                    aio_dial((int)NameList.TYPE_ADDFIP, Dns.GetHostAddresses(Global.Settings.STUN_Server)[0].ToString());
            }

            foreach (var rule in mode.FullRule)
            {
                aio_dial((int)NameList.TYPE_ADDFIP, rule);
            }
        }

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

string GetHost()
        {
            if (_connector.EndPoint is IPEndPoint)
                return (_connector.EndPoint as IPEndPoint).Address.ToString();
            else if (_connector.EndPoint is DnsEndPoint)
                return (_connector.EndPoint as DnsEndPoint).Host;
            else
                return null;
        }

19 View Source File : HotReloader.cs
License : MIT License
Project Creator : AndreiMisiukevich

public ReloaderStartupInfo Run(Application app, Configuration config = null)
        {
            config = config ?? new Configuration();
            var devicePort = config.DeviceUrlPort;
            _codeReloadingEnabled = config.CodeReloadingEnabled;

            Stop();
            App = app;
            IsRunning = true;

            if (app != null)
            {
                _replacedemblies.Add(app.GetType().replacedembly);
            }
            foreach (var asm in config.Appreplacedemblies ?? new replacedembly[0])
            {
                _replacedemblies.Add(asm);
            }

            TrySubscribeRendererPropertyChanged("Platform.RendererProperty", "CellRenderer.RendererProperty", "CellRenderer.RealCellProperty", "CellRenderer.s_realCellProperty");

            _resourceMapping = new ConcurrentDictionary<string, ReloadItem>();

            if (HasCodegenAttribute(app))
            {
                InitializeElement(app, true);
            }

            HttpListener listener = null;
            var maxPort = devicePort + 1000;
            while (devicePort < maxPort)
            {
                listener = new HttpListener
                {
                    Prefixes =
                    {
                        $"http://*:{devicePort}/"
                    }
                };
                try
                {
                    listener.Start();
                    break;
                }
                catch
                {
                    ++devicePort;
                }
            }

            _daemonThread = new Thread(() =>
            {
                do
                {
                    var context = listener.GetContext();
                    ThreadPool.QueueUserWorkItem((_) => HandleReloadRequest(context));
                } while (true);
            });
            _daemonThread.Start();

            var addresses = NetworkInterface.GetAllNetworkInterfaces()
                          .SelectMany(x => x.GetIPProperties().UnicastAddresses)
                          .Where(x => x.Address.AddressFamily == AddressFamily.InterNetwork)
                          .Select(x => x.Address.MapToIPv4())
                          .Where(x => x.ToString() != "127.0.0.1")
                          .ToArray();

            foreach (var addr in addresses)
            {
                Console.WriteLine($"### [OLD] HOTRELOAD DEVICE's IP: {addr} ###");
            }

            Console.WriteLine($"### HOTRELOAD STARTED ON DEVICE's PORT: {devicePort} ###");

            var loadXaml = XamlLoaderType.GetMethods(BindingFlags.Static | BindingFlags.Public)
                ?.FirstOrDefault(m => m.Name == "Load" && m.GetParameters().Length == 3);

            _loadXaml = (obj, xaml, isPreviewer) =>
            {
                var isPreview = isPreviewer ?? config.PreviewerDefaultMode == PreviewerMode.On;
                if (loadXaml != null && isPreview)
                {
                    loadXaml.Invoke(null, new object[] { obj, xaml, true });
                    return;
                }
                obj.LoadFromXaml(xaml);
            };

            Task.Run(async () =>
            {
                var portsRange = Enumerable.Range(15000, 2).Union(Enumerable.Range(17502, 18));

                var isFirstTry = true;

                while (IsRunning)
                {
                    foreach (var possiblePort in portsRange.Take(isFirstTry ? 20 : 5))
                    {
                        if (Device.RuntimePlatform == Device.Android || Device.RuntimePlatform == Device.Tizen)
                        {
                            try
                            {
                                using (var client = new UdpClient { EnableBroadcast = true })
                                {
                                    client.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Broadcast, 1);
                                    var emulatorData = Encoding.ASCII.GetBytes($"http://127.0.0.1:{devicePort}");
                                    client.Send(emulatorData, emulatorData.Length, new IPEndPoint(IPAddress.Parse("10.0.2.2"), possiblePort));
                                    client.Send(emulatorData, emulatorData.Length, new IPEndPoint(IPAddress.Parse("10.0.3.2"), possiblePort));
                                }
                            }
                            catch { }
                        }

                        foreach (var ip in addresses)
                        {
                            try
                            {
                                var remoteIp = new IPEndPoint(config.ExtensionIpAddress, possiblePort);
                                using (var client = new UdpClient(new IPEndPoint(ip, 0)) { EnableBroadcast = true })
                                {
                                    client.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Broadcast, 1);
                                    var data = Encoding.ASCII.GetBytes($"http://{ip}:{devicePort}");
                                    client.Send(data, data.Length, remoteIp);
                                }
                            }
                            catch { }
                        }
                    }
                    isFirstTry = false;
                    await Task.Delay(12000);
                }
            });

            if (config.CodeReloadingEnabled)
            {
                Task.Run(() =>
                {
                    try
                    {
                        foreach (var asm in _replacedemblies)
                        {
                            HotCompiler.Current.TryLoadreplacedembly(asm);
                        }
                        var testType = HotCompiler.Current.Compile("public clreplaced TestHotCompiler { }", "TestHotCompiler");
                        HotCompiler.IsSupported = testType != null;
                    }
                    catch
                    {
                        HotCompiler.IsSupported = false;
                    }
                });
            }
            else
            {
                HotCompiler.IsSupported = false;
            }

            return new ReloaderStartupInfo
            {
                SelectedDevicePort = devicePort,
                IPAddresses = addresses
            };
        }

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

public bool IsOverIpLimit(string host)
        {
            if (NetworkOptions.MaxPeersPerIpAddress == 0 || host.Equals(IPAddress.Loopback.ToString()))
                return false;
                
            int initiatedHandshakes = 0;
            if (HandshakingPeers.TryGetValue(host, out var handshakes))
                initiatedHandshakes = handshakes.Count;
                
            int peersFromIpCount = GetPeersByHost(host).Count;
            if (peersFromIpCount + initiatedHandshakes >= NetworkOptions.MaxPeersPerIpAddress)
            {
                Logger.LogWarning($"Max peers from {host} exceeded, current count {peersFromIpCount} " +
                                  $"(max. per ip {NetworkOptions.MaxPeersPerIpAddress}).");

                return true;
            }

            return false;
        }

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

internal Task StartListeningAsync()
        {
            ServerServiceDefinition serviceDefinition = PeerService.BindService(_serverService);

            if (_authInterceptor != null)
                serviceDefinition = serviceDefinition.Intercept(_authInterceptor);

            var serverOptions = new List<ChannelOption>
            {
                new ChannelOption(ChannelOptions.MaxSendMessageLength, GrpcConstants.DefaultMaxSendMessageLength),
                new ChannelOption(ChannelOptions.MaxReceiveMessageLength, GrpcConstants.DefaultMaxReceiveMessageLength)
            };

            // setup service
            _server = new Server(serverOptions);
            _server.Services.Add(serviceDefinition);
            
            var serverCredentials = CreateCredentials();
            
            // setup encrypted endpoint	
            _server.Ports.Add(new ServerPort(IPAddress.Any.ToString(), NetworkOptions.ListeningPort, serverCredentials));
            
            return Task.Run(() =>
            {
                _server.Start();
                
                foreach (var port in _server.Ports)
                    Logger.LogDebug($"Server listening on {port.Host}:{port.BoundPort}.");
            });
        }

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

public static List<string> GetHostIPAddress()
        {
            List<string> lstIPAddress = new List<string>();
            try
            {
                IPHostEntry IpEntry = Dns.GetHostEntry(Dns.GetHostName());
                foreach (IPAddress ipa in IpEntry.AddressList)
                {
                    if (ipa.AddressFamily == AddressFamily.InterNetwork)
                        lstIPAddress.Add(ipa.ToString());
                }
            }
            catch (Exception ex)
            {
                SaveLog(ex.Message, ex);
            }
            return lstIPAddress;
        }

19 View Source File : AddressUtils.cs
License : MIT License
Project Creator : aguang-xyz

public static string GetServerAddress()
        {
            var host = Dns.GetHostEntry(Dns.GetHostName());
            
            foreach (var address in host.AddressList)
            {
                if (address.AddressFamily == AddressFamily.InterNetwork)
                {
                    var ip = address.ToString();

                    if (ip != "127.0.0.1")
                    {
                        return $"http://{address}:{GlobalConstants.ServerPort}";
                    }
                }
            }

            throw new InvalidOperationException("No IPv4 address for the current device");
        }

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

private void DoClient(ConnectClient client)
        {
            SessionServer session = null;
            string addrIP = ((IPEndPoint)client.Client.Client.RemoteEndPoint).Address.ToString();
            try
            {
                try
                {
                    if (Repository.CheckIsBanIP(addrIP))
                    {
                        Loger.Log("Abort connect BanIP " + addrIP);
                    }
                    else
                    {
                        Loger.Log($"New connect {addrIP} (connects: {ActiveClientCount})");
                        session = new SessionServer();
                        lock (Sessions)
                        {
                            Sessions.Add(session);
                        }
                        session.Do(client, SessionsAction);
                    }
                }
                catch (ObjectDisposedException)
                {
                    Loger.Log("Abort connect Relogin " + addrIP);
                }
                catch (Transfer.ConnectClient.ConnectSilenceTimeOutException)
                {
                    Loger.Log("Abort connect TimeOut " + addrIP);
                }
                catch (Exception e)
                {
                    if (!(e is SocketException) && !(e.InnerException is SocketException)
                        && !(e is Transfer.ConnectClient.ConnectNotConnectedException) && !(e.InnerException is Transfer.ConnectClient.ConnectNotConnectedException))
                    {
                        ExceptionUtil.ExceptionLog(e, "Server Exception");
                    }
                }
                //if (LogMessage != null) LogMessage("End connect");
            }
            finally
            {
                Interlocked.Decrement(ref _ActiveClientCount);
                Loger.Log($"Close connect {addrIP}{(session == null ? "" : " " + session?.GetNameWhoConnect())} (connects: {ActiveClientCount})");
                try
                {
                    if (session != null)
                    {
                        session.Dispose();
                    }
                }
                catch
                { }
            }
        }

19 View Source File : UDPListenerManager.cs
License : MIT License
Project Creator : akihiro0105

private void ReceiveCallback(IAsyncResult result)
        {
            var udp = (UdpClient) result.AsyncState;
            IPEndPoint remote = null;
            var bytes = udp.EndReceive(result, ref remote);
            if (ListenerMessageEvent != null)
                ListenerMessageEvent(Encoding.UTF8.GetString(bytes), remote.Address.ToString());
            if (ListenerByteEvent != null) ListenerByteEvent(bytes, remote.Address.ToString());
            udp.BeginReceive(ReceiveCallback, udp);
        }

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

private bool IsPermitedAddress(IPEndPoint remote)
		{
			if (PermitAddress == null)
				return true;

			return (remote.Address.ToString() == PermitAddress.ToString());
		}

19 View Source File : Form1.cs
License : Apache License 2.0
Project Creator : abaga129

private void ConnectToServer()
        {
            try
            {
                hostAddr = Dns.GetHostEntry(AddressBox.Text);
                Server = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                Server.Connect(hostAddr.AddressList[0].ToString(), 5005);

                StateObject state = new StateObject();
                state.client = Server;

                Server.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0, new AsyncCallback(ReceiveCallback), state);
                StatusLabel.Text = "Connected To Server @ " + AddressBox.Text;
                
            }
            catch (Exception)
            {
                StatusLabel.Text = "Could Not Connect To " + AddressBox.Text;
            }
        }

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

public override void ConfigureServices(ServiceConfigurationContext context)
        {
            // Tubumu.Meeting.Server 不是 AbpModule,故手工注册。
            context.Services.AddTransient<MeetingHub>();

            var configuration = BuildConfiguration();

            // Mediasoup
            var mediasoupStartupSettings = configuration.GetSection("MediasoupStartupSettings").Get<MediasoupStartupSettings>();
            var mediasoupSettings = configuration.GetSection("MediasoupSettings").Get<MediasoupSettings>();
            var workerSettings = mediasoupSettings.WorkerSettings;
            var routerSettings = mediasoupSettings.RouterSettings;
            var webRtcTransportSettings = mediasoupSettings.WebRtcTransportSettings;
            var plainTransportSettings = mediasoupSettings.PlainTransportSettings;
            context.Services.AddMediasoup(options =>
            {
                // MediasoupStartupSettings
                if (mediasoupStartupSettings != null)
                {
                    options.MediasoupStartupSettings.MediasoupVersion = mediasoupStartupSettings.MediasoupVersion;
                    options.MediasoupStartupSettings.WorkerPath = mediasoupStartupSettings.WorkerPath;
                    options.MediasoupStartupSettings.NumberOfWorkers = !mediasoupStartupSettings.NumberOfWorkers.HasValue || mediasoupStartupSettings.NumberOfWorkers <= 0 ? Environment.ProcessorCount : mediasoupStartupSettings.NumberOfWorkers;
                }

                // WorkerSettings
                if (workerSettings != null)
                {
                    options.MediasoupSettings.WorkerSettings.LogLevel = workerSettings.LogLevel;
                    options.MediasoupSettings.WorkerSettings.LogTags = workerSettings.LogTags;
                    options.MediasoupSettings.WorkerSettings.RtcMinPort = workerSettings.RtcMinPort;
                    options.MediasoupSettings.WorkerSettings.RtcMaxPort = workerSettings.RtcMaxPort;
                    options.MediasoupSettings.WorkerSettings.DtlsCertificateFile = workerSettings.DtlsCertificateFile;
                    options.MediasoupSettings.WorkerSettings.DtlsPrivateKeyFile = workerSettings.DtlsPrivateKeyFile;
                }

                // RouteSettings
                if (routerSettings != null && !routerSettings.RtpCodecCapabilities.IsNullOrEmpty())
                {
                    options.MediasoupSettings.RouterSettings = routerSettings;

                    // Fix RtpCodecCapabilities[x].Parameters 。从配置文件反序列化时将数字转换成了字符串,这里进行修正。
                    foreach (var codec in routerSettings.RtpCodecCapabilities.Where(m => m.Parameters != null))
                    {
                        foreach (var key in codec.Parameters.Keys.ToArray())
                        {
                            var value = codec.Parameters[key];
                            if (value != null && Int32.TryParse(value.ToString(), out var intValue))
                            {
                                codec.Parameters[key] = intValue;
                            }
                        }
                    }
                }

                // WebRtcTransportSettings
                if (webRtcTransportSettings != null)
                {
                    options.MediasoupSettings.WebRtcTransportSettings.ListenIps = webRtcTransportSettings.ListenIps;
                    options.MediasoupSettings.WebRtcTransportSettings.InitialAvailableOutgoingBitrate = webRtcTransportSettings.InitialAvailableOutgoingBitrate;
                    options.MediasoupSettings.WebRtcTransportSettings.MinimumAvailableOutgoingBitrate = webRtcTransportSettings.MinimumAvailableOutgoingBitrate;
                    options.MediasoupSettings.WebRtcTransportSettings.MaxSctpMessageSize = webRtcTransportSettings.MaxSctpMessageSize;

                    // 如果没有设置 ListenIps 则获取本机所有的 IPv4 地址进行设置。
                    var listenIps = options.MediasoupSettings.WebRtcTransportSettings.ListenIps;
                    if (listenIps.IsNullOrEmpty())
                    {
                        var localIPv4IPAddresses = IPAddressExtensions.GetLocalIPAddresses(AddressFamily.InterNetwork).Where(m => m != IPAddress.Loopback);
                        if (localIPv4IPAddresses.IsNullOrEmpty())
                        {
                            throw new ArgumentException("无法获取本机 IPv4 配置 WebRtcTransport。");
                        }

                        listenIps = (from ip in localIPv4IPAddresses
                                     let ipString = ip.ToString()
                                     select new TransportListenIp
                                     {
                                         Ip = ipString,
                                         AnnouncedIp = ipString
                                     }).ToArray();
                        options.MediasoupSettings.WebRtcTransportSettings.ListenIps = listenIps;
                    }
                    else
                    {
                        var localIPv4IPAddress = IPAddressExtensions.GetLocalIPv4IPAddress();
                        if (localIPv4IPAddress == null)
                        {
                            throw new ArgumentException("无法获取本机 IPv4 配置 WebRtcTransport。");
                        }

                        foreach (var listenIp in listenIps)
                        {
                            if(string.IsNullOrWhiteSpace(listenIp.AnnouncedIp))
                            {
                                // 如果没有设置 AnnouncedIp:
                                // 如果 Ip 属性的值不是 Any 则赋值为 Ip 属性的值,否则取本机的任意一个 IPv4 地址进行设置。(注意:可能获取的并不是正确的 IP)
                                listenIp.AnnouncedIp = listenIp.Ip == IPAddress.Any.ToString() ? localIPv4IPAddress.ToString() : listenIp.Ip;
                            }
                        }
                    }
                }

                // PlainTransportSettings
                if (plainTransportSettings != null)
                {
                    options.MediasoupSettings.PlainTransportSettings.ListenIp = plainTransportSettings.ListenIp;
                    options.MediasoupSettings.PlainTransportSettings.MaxSctpMessageSize = plainTransportSettings.MaxSctpMessageSize;

                    var localIPv4IPAddress = IPAddressExtensions.GetLocalIPv4IPAddress();
                    if (localIPv4IPAddress == null)
                    {
                        throw new ArgumentException("无法获取本机 IPv4 配置 PlainTransport。");
                    }

                    var listenIp = options.MediasoupSettings.PlainTransportSettings.ListenIp;
                    if (listenIp == null)
                    {
                        listenIp = new TransportListenIp
                        {
                            Ip = localIPv4IPAddress.ToString(),
                            AnnouncedIp = localIPv4IPAddress.ToString(),
                        };
                        options.MediasoupSettings.PlainTransportSettings.ListenIp = listenIp;
                    }
                    else if (string.IsNullOrWhiteSpace(listenIp.AnnouncedIp))
                    {
                        // 如果没有设置 AnnouncedIp:
                        // 如果 Ip 属性的值不是 Any 则赋值为 Ip 属性的值,否则取本机的任意一个 IPv4 地址进行设置。(注意:可能获取的并不是正确的 IP)
                        listenIp.AnnouncedIp = listenIp.Ip == IPAddress.Any.ToString() ? localIPv4IPAddress.ToString() : listenIp.Ip;
                    }
                }
            });

            // Meeting server
            context.Services.AddMeetingServer(options =>
            {
                options.ServeMode = ServeMode.Open;
            });

            // SignalR
            context.Services.AddSignalR(options =>
            {
                options.EnableDetailedErrors = true;
            })
            .AddJsonProtocol(options =>
            {
                options.PayloadSerializerOptions.Converters.Add(new JsonStringEnumMemberConverter());
                options.PayloadSerializerOptions.PropertyNamingPolicy = JsonNamingPolicy.CamelCase;
            });
        }

19 View Source File : Util.cs
License : MIT License
Project Creator : 499116344

public static string GetHostAddresses(string hostname)
        {
            var ips = Dns.GetHostAddresses(hostname);

            return ips[0].ToString();
        }

19 View Source File : PortForm.cs
License : MIT License
Project Creator : AlexGyver

private string getLocalIP() {
      IPHostEntry host;
      string localIP = "?";
      host = Dns.GetHostEntry(Dns.GetHostName());
      foreach (IPAddress ip in host.AddressList) {
        if (ip.AddressFamily == AddressFamily.InterNetwork) {
          localIP = ip.ToString();
        }
      }
      return localIP;
    }

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

public static void ProcessPacket(ConnectionListener connectionListener, ClientPacket packet, IPEndPoint endPoint)
        {
            if (connectionListener.ListenerEndpoint.Port == ConfigManager.Config.Server.Network.Port + 1)
            {
                ServerPerformanceMonitor.RestartEvent(ServerPerformanceMonitor.MonitorType.ProcessPacket_1);
                if (packet.Header.Flags.HasFlag(PacketHeaderFlags.ConnectResponse))
                {
                    packetLog.Debug($"{packet}, {endPoint}");
                    PacketInboundConnectResponse connectResponse = new PacketInboundConnectResponse(packet);

                    // This should be set on the second packet to the server from the client.
                    // This completes the three-way handshake.
                    sessionLock.EnterReadLock();
                    Session session = null;
                    try
                    {
                        session =
                            (from k in sessionMap
                             where
                                 k != null &&
                                 k.State == SessionState.AuthConnectResponse &&
                                 k.Network.ConnectionData.ConnectionCookie == connectResponse.Check &&
                                 k.EndPoint.Address.Equals(endPoint.Address)
                             select k).FirstOrDefault();
                    }
                    finally
                    {
                        sessionLock.ExitReadLock();
                    }
                    if (session != null)
                    {
                        session.State = SessionState.AuthConnected;
                        session.Network.sendResync = true;
                        AuthenticationHandler.HandleConnectResponse(session);
                    }

                }
                else if (packet.Header.Id == 0 && packet.Header.HasFlag(PacketHeaderFlags.CICMDCommand))
                {
                    // TODO: Not sure what to do with these packets yet
                }
                else
                {
                    log.ErrorFormat("Packet from {0} rejected. Packet sent to listener 1 and is not a ConnectResponse or CICMDCommand", endPoint);
                }
                ServerPerformanceMonitor.RegisterEventEnd(ServerPerformanceMonitor.MonitorType.ProcessPacket_1);
            }
            else // ConfigManager.Config.Server.Network.Port + 0
            {
                ServerPerformanceMonitor.RestartEvent(ServerPerformanceMonitor.MonitorType.ProcessPacket_0);
                if (packet.Header.HasFlag(PacketHeaderFlags.LoginRequest))
                {
                    packetLog.Debug($"{packet}, {endPoint}");
                    if (GetAuthenticatedSessionCount() >= ConfigManager.Config.Server.Network.MaximumAllowedSessions)
                    {
                        log.InfoFormat("Login Request from {0} rejected. Server full.", endPoint);
                        SendLoginRequestReject(connectionListener, endPoint, CharacterError.LogonServerFull);
                    }
                    else if (ServerManager.ShutdownInProgress)
                    {
                        log.InfoFormat("Login Request from {0} rejected. Server is shutting down.", endPoint);
                        SendLoginRequestReject(connectionListener, endPoint, CharacterError.ServerCrash1);
                    }
                    else if (ServerManager.ShutdownInitiated && (ServerManager.ShutdownTime - DateTime.UtcNow).TotalMinutes < 2)
                    {
                        log.InfoFormat("Login Request from {0} rejected. Server shutting down in less than 2 minutes.", endPoint);
                        SendLoginRequestReject(connectionListener, endPoint, CharacterError.ServerCrash1);
                    }
                    else
                    {
                        log.DebugFormat("Login Request from {0}", endPoint);

                        var ipAllowsUnlimited = ConfigManager.Config.Server.Network.AllowUnlimitedSessionsFromIPAddresses.Contains(endPoint.Address.ToString());
                        if (ipAllowsUnlimited || ConfigManager.Config.Server.Network.MaximumAllowedSessionsPerIPAddress == -1 || GetSessionEndpointTotalByAddressCount(endPoint.Address) < ConfigManager.Config.Server.Network.MaximumAllowedSessionsPerIPAddress)
                        {
                            var session = FindOrCreateSession(connectionListener, endPoint);
                            if (session != null)
                            {
                                if (session.State == SessionState.AuthConnectResponse)
                                {
                                    // connect request packet sent to the client was corrupted in transit and session entered an unspecified state.
                                    // ignore the request and remove the broken session and the client will start a new session.
                                    RemoveSession(session);
                                    log.Warn($"Bad handshake from {endPoint}, aborting session.");
                                }

                                session.ProcessPacket(packet);
                            }
                            else
                            {
                                log.InfoFormat("Login Request from {0} rejected. Failed to find or create session.", endPoint);
                                SendLoginRequestReject(connectionListener, endPoint, CharacterError.LogonServerFull);
                            }
                        }
                        else
                        {
                            log.InfoFormat("Login Request from {0} rejected. Session would exceed MaximumAllowedSessionsPerIPAddress limit.", endPoint);
                            SendLoginRequestReject(connectionListener, endPoint, CharacterError.LogonServerFull);
                        }
                    }
                }
                else if (sessionMap.Length > packet.Header.Id)
                {
                    var session = sessionMap[packet.Header.Id];
                    if (session != null)
                    {
                        if (session.EndPoint.Equals(endPoint))
                            session.ProcessPacket(packet);
                        else
                            log.DebugFormat("Session for Id {0} has IP {1} but packet has IP {2}", packet.Header.Id, session.EndPoint, endPoint);
                    }
                    else
                    {
                        log.DebugFormat("Unsolicited Packet from {0} with Id {1}", endPoint, packet.Header.Id);
                    }
                }
                else
                {
                    log.DebugFormat("Unsolicited Packet from {0} with Id {1}", endPoint, packet.Header.Id);
                }
                ServerPerformanceMonitor.RegisterEventEnd(ServerPerformanceMonitor.MonitorType.ProcessPacket_0);
            }
        }

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

internal override string RecordDataToString()
		{
			return Address.ToString();
		}

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

string GetHostForAuthentication()
        {
            if (_remote == null)
                throw new ArgumentNullException("Remote endpoint is not set");
            else if (_remote is DnsEndPoint)
                return (_remote as DnsEndPoint).Host;
            else if (_remote is IPEndPoint)
                return (_remote as IPEndPoint).Address.ToString();

            throw new InvalidOperationException("Cannot get remote host");
        }

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

protected internal void Listen()
        {
            try
            {
                _tcpListener = new TcpListener(IPAddress.Any, Port);
                _tcpListener.Start();
                Task.Run(Sender);
                Started?.Invoke();

                while (true)
                {
                    TcpClient tcpClient = _tcpListener.AcceptTcpClient();

                    var ip = ((IPEndPoint)tcpClient.Client.RemoteEndPoint).Address.ToString();
                    if (!_permittedIp.Contains(ip))
                    {
                        tcpClient.Close();
                        continue;
                    }

                    AdminPanelClient adminPanelClient = new AdminPanelClient(tcpClient, this);
                    adminPanelClient.Token = PermittedToken;

                    Thread clientThread = new Thread(adminPanelClient.Process);
                    clientThread.Start();
                }
            }
            catch (Exception ex)
            {
                Disconnect();
                Disconnected?.Invoke();
            }
        }

19 View Source File : NetworkHelper.cs
License : MIT License
Project Creator : admaiorastudio

public static string GetLocalIPAddress()
        {
            var host = Dns.GetHostEntry(Dns.GetHostName());
            foreach (var ip in host.AddressList)
            {
                if (ip.AddressFamily == AddressFamily.InterNetwork)
                {
                    return ip.ToString();
                }
            }

            throw new Exception("No network adapters with an IPv4 address in the system!");
        }

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

public static bool TryDecode(byte[] buffer, int offset, out AnnounceResponseMessage message)
        {
            int action;
            int transactionId;
            int interval;
            int leechers;
            int seeders;
            IPEndPoint endpoint;
            IDictionary<string, IPEndPoint> peers = new Dictionary<string, IPEndPoint>();

            message = null;

            if (buffer != null &&
                buffer.Length >= offset + ActionLength + TransactionIdLength + IntervalLength + LeechersLength + SeedersLength &&
                offset >= 0)
            {
                action = Message.ReadInt(buffer, ref offset);
                transactionId = Message.ReadInt(buffer, ref offset);
                interval = Message.ReadInt(buffer, ref offset);
                leechers = Message.ReadInt(buffer, ref offset);
                seeders = Message.ReadInt(buffer, ref offset);

                if (action == (int)TrackingAction.Announce &&
                    transactionId >= 0 &&
                    interval > 0 &&
                    leechers >= 0 &&
                    seeders >= 0)
                {
                    while (offset <= buffer.Length - IpAddressLength - PortLength)
                    {
                        endpoint = Message.ReadEndpoint(buffer, ref offset);

                        if (!peers.ContainsKey(endpoint.Address.ToString()))
                        {
                            peers.Add(endpoint.Address.ToString(), endpoint);
                        }
                    }

                    message = new AnnounceResponseMessage(transactionId, TimeSpan.FromSeconds(interval), leechers, seeders, peers.Values);
                }
            }

            return message != null;
        }

19 View Source File : Utility.IP.cs
License : MIT License
Project Creator : 7Bytes-Studio

public static string GetRealPublicIP()
            {
                var hostName = Dns.GetHostName();
                var addresses = Dns.GetHostAddresses(hostName);
                string ip = string.Empty;
                for (int i = 0; i < addresses.Length; i++)
                {
                    if (!string.IsNullOrEmpty(ip = g_IpRegex.Match(addresses[i].ToString()).Groups[0].Value))
                    {
                        return ip.Trim();
                    }
                }
                return string.Empty;
            }

19 View Source File : SharedServicesRegistration.cs
License : MIT License
Project Creator : AlphaYu

public virtual void AddEventBusSubscribers<TSubscriber>()
            where TSubscriber : clreplaced, ICapSubscribe
        {
            var tableNamePrefix = "Cap";
            var groupName = $"cap.{_serviceInfo.ShortName}.{_environment.EnvironmentName.ToLower()}";

            //add skyamp
            _services.AddSkyApmExtensions().AddCap();

            _services.AddSingleton<TSubscriber>();

            var rabbitMqConfig = _configuration.GetRabbitMqSection().Get<RabbitMqConfig>();
            _services.AddCap(x =>
            {
                //如果你使用的 EF 进行数据操作,你需要添加如下配置:
                //可选项,你不需要再次配置 x.UseSqlServer 了
                x.UseEnreplacedyFramework<AdncDbContext>(option =>
                {
                    option.TableNamePrefix = tableNamePrefix;
                });
                //CAP支持 RabbitMQ、Kafka、AzureServiceBus 等作为MQ,根据使用选择配置:
                x.UseRabbitMQ(option =>
                {
                    option.HostName = rabbitMqConfig.HostName;
                    option.VirtualHost = rabbitMqConfig.VirtualHost;
                    option.Port = rabbitMqConfig.Port;
                    option.UserName = rabbitMqConfig.UserName;
                    option.Preplacedword = rabbitMqConfig.Preplacedword;
                });
                x.Version = _serviceInfo.Version;
                //默认值:cap.queue.{程序集名称},在 RabbitMQ 中映射到 Queue Names。
                x.DefaultGroupName = groupName;
                //默认值:60 秒,重试 & 间隔
                //在默认情况下,重试将在发送和消费消息失败的 4分钟后 开始,这是为了避免设置消息状态延迟导致可能出现的问题。
                //发送和消费消息的过程中失败会立即重试 3 次,在 3 次以后将进入重试轮询,此时 FailedRetryInterval 配置才会生效。
                x.FailedRetryInterval = 60;
                //默认值:50,重试的最大次数。当达到此设置值时,将不会再继续重试,通过改变此参数来设置重试的最大次数。
                x.FailedRetryCount = 50;
                //默认值:NULL,重试阈值的失败回调。当重试达到 FailedRetryCount 设置的值的时候,将调用此 Action 回调
                //,你可以通过指定此回调来接收失败达到最大的通知,以做出人工介入。例如发送邮件或者短信。
                x.FailedThresholdCallback = (failed) =>
                {
                    //todo
                };
                //默认值:24*3600 秒(1天后),成功消息的过期时间(秒)。
                //当消息发送或者消费成功时候,在时间达到 SucceedMessageExpiredAfter 秒时候将会从 Persistent 中删除,你可以通过指定此值来设置过期的时间。
                x.SucceedMessageExpiredAfter = 24 * 3600;
                //默认值:1,消费者线程并行处理消息的线程数,当这个值大于1时,将不能保证消息执行的顺序。
                x.ConsumerThreadCount = 1;
                x.UseDashboard(x =>
                {
                    x.PathMatch = $"/{_serviceInfo.ShortName}/cap";
                    x.Authorization = new IDashboardAuthorizationFilter[] {
                        new LocalRequestsOnlyAuthorizationFilter()
                        ,
                        new CapDashboardAuthorizationFilter()
                    };
                });
                //必须是生产环境才注册cap服务到consul
                if ((_environment.IsProduction() || _environment.IsStaging()))
                {
                    x.UseDiscovery(discoverOptions =>
                    {
                        var consulConfig = _configuration.GetConsulSection().Get<ConsulConfig>();
                        var consulAdderss = new Uri(consulConfig.ConsulUrl);

                        var hostIps = NetworkInterface
                                                                        .GetAllNetworkInterfaces()
                                                                        .Where(network => network.OperationalStatus == OperationalStatus.Up)
                                                                        .Select(network => network.GetIPProperties())
                                                                        .OrderByDescending(properties => properties.GatewayAddresses.Count)
                                                                        .SelectMany(properties => properties.UnicastAddresses)
                                                                        .Where(address => !IPAddress.IsLoopback(address.Address) && address.Address.AddressFamily == AddressFamily.InterNetwork)
                                                                        .ToArray();

                        var currenServerAddress = hostIps.First().Address.MapToIPv4().ToString();

                        discoverOptions.DiscoveryServerHostName = consulAdderss.Host;
                        discoverOptions.DiscoveryServerPort = consulAdderss.Port;
                        discoverOptions.CurrentNodeHostName = currenServerAddress;
                        discoverOptions.CurrentNodePort = 80;
                        discoverOptions.NodeId = DateTime.Now.Ticks.ToString();
                        discoverOptions.NodeName = _serviceInfo.FullName.Replace("webapi", "cap");
                        discoverOptions.MatchPath = $"/{_serviceInfo.ShortName}/cap";
                    });
                }
            });
        }

19 View Source File : ViewerServer.cs
License : MIT License
Project Creator : admaiorastudio

private string GetLocalIPAddress()
        {
            var host = Dns.GetHostEntry(Dns.GetHostName());
            foreach (var ip in host.AddressList)
            {
                if (ip.AddressFamily == AddressFamily.InterNetwork)
                {
                    return ip.ToString();
                }
            }

            throw new Exception("No network adapters with an IPv4 address in the system!");
        }

19 View Source File : OpenVPNSession.cs
License : GNU General Public License v3.0
Project Creator : Amebis

protected override void DoRun()
        {
            Wizard.Dispatcher.Invoke(DispatcherPriority.Normal, (Action)(() => Wizard.TaskCount++));
            try
            {
                try
                {
                    // Start OpenVPN management interface on IPv4 loopack interface (any TCP free port).
                    var mgmtServer = new TcpListener(IPAddress.Loopback, 0);
                    mgmtServer.Start();
                    try
                    {
                        try
                        {
                            // Purge stale log files.
                            var timestamp = DateTime.UtcNow.Subtract(new TimeSpan(30, 0, 0, 0));
                            foreach (var f in Directory.EnumerateFiles(WorkingFolder, "*.txt", SearchOption.TopDirectoryOnly))
                            {
                                SessionAndWindowInProgress.Token.ThrowIfCancellationRequested();
                                if (File.GetLastWriteTimeUtc(f) <= timestamp)
                                {
                                    try { File.Delete(LogPath); }
                                    catch { }
                                }
                            }
                        }
                        catch (OperationCanceledException) { throw; }
                        catch (Exception) { /* Failure to remove stale log files is not fatal. */ }

                        try
                        {
                            // Save OpenVPN configuration file.
                            using (var fs = new FileStream(
                                ConfigurationPath,
                                FileMode.Create,
                                FileAccess.Write,
                                FileShare.Read,
                                1048576,
                                FileOptions.SequentialScan))
                            using (var sw = new StreamWriter(fs))
                            {
                                // Save profile's configuration to file.

                                if (Properties.SettingsEx.Default.OpenVPNRemoveOptions is StringCollection openVPNRemoveOptions)
                                {
                                    // Remove options on the OpenVPNRemoveOptions list on the fly.
                                    using (var sr = new StringReader(ProfileConfig))
                                    {
                                        string inlineTerm = null;
                                        bool inlineRemove = false;
                                        for (; ; )
                                        {
                                            var line = sr.ReadLine();
                                            if (line == null)
                                                break;

                                            var trimmedLine = line.Trim();
                                            if (!string.IsNullOrEmpty(trimmedLine))
                                            {
                                                // Not an empty line.
                                                if (inlineTerm == null)
                                                {
                                                    // Not inside an inline option block = Regular parsing mode.
                                                    if (!trimmedLine.StartsWith("#") &&
                                                        !trimmedLine.StartsWith(";"))
                                                    {
                                                        // Not a comment.
                                                        var option = eduOpenVPN.Configuration.ParseParams(trimmedLine);
                                                        if (option.Count > 0)
                                                        {
                                                            if (option[0].StartsWith("<") && !option[0].StartsWith("</") && option[0].EndsWith(">"))
                                                            {
                                                                // Start of an inline option.
                                                                var o = option[0].Substring(1, option[0].Length - 2);
                                                                inlineTerm = "</" + o + ">";
                                                                inlineRemove = openVPNRemoveOptions.Contains(o);
                                                                if (inlineRemove)
                                                                {
                                                                    sw.WriteLine("# Commented by OpenVPNRemoveOptions setting:");
                                                                    line = "# " + line;
                                                                }
                                                            }
                                                            else if (openVPNRemoveOptions.Contains(option[0]))
                                                            {
                                                                sw.WriteLine("# Commented by OpenVPNRemoveOptions setting:");
                                                                line = "# " + line;
                                                            }
                                                        }
                                                    }
                                                }
                                                else
                                                {
                                                    // Inside an inline option block.
                                                    if (inlineRemove)
                                                    {
                                                        // Remove the inline option content.
                                                        line = "# " + line;
                                                    }

                                                    if (trimmedLine == inlineTerm)
                                                    {
                                                        // Inline option terminator found. Returning to regular parsing mode.
                                                        inlineTerm = null;
                                                    }
                                                }
                                            }

                                            sw.WriteLine(line);
                                        }
                                    }
                                }
                                else
                                    sw.Write(ProfileConfig);

                                // Append eduVPN Client specific configuration directives.
                                sw.WriteLine();
                                sw.WriteLine();
                                sw.WriteLine("# eduVPN Client for Windows");

                                // Introduce ourself (to OpenVPN server).
                                var replacedembly = replacedembly.GetExecutingreplacedembly();
                                var replacedemblyreplacedleAttribute = Attribute.GetCustomAttributes(replacedembly, typeof(replacedemblyreplacedleAttribute)).SingleOrDefault() as replacedemblyreplacedleAttribute;
                                var replacedemblyVersion = replacedembly?.GetName()?.Version;
                                sw.WriteLine("setenv IV_GUI_VER " + eduOpenVPN.Configuration.EscapeParamValue(replacedemblyreplacedleAttribute?.replacedle + " " + replacedemblyVersion?.ToString()));

                                // Configure log file (relative to WorkingFolder).
                                sw.WriteLine("log-append " + eduOpenVPN.Configuration.EscapeParamValue(ConnectionId + ".txt"));

                                // Configure interaction between us and openvpn.exe.
                                sw.WriteLine("management " + eduOpenVPN.Configuration.EscapeParamValue(((IPEndPoint)mgmtServer.LocalEndpoint).Address.ToString()) + " " + eduOpenVPN.Configuration.EscapeParamValue(((IPEndPoint)mgmtServer.LocalEndpoint).Port.ToString()) + " stdin");
                                sw.WriteLine("management-client");
                                sw.WriteLine("management-hold");
                                sw.WriteLine("management-query-preplacedwords");
                                sw.WriteLine("management-query-remote");

                                // Configure client certificate.
                                sw.WriteLine("cert " + eduOpenVPN.Configuration.EscapeParamValue(ConnectingProfile.Server.ClientCertificatePath));
                                sw.WriteLine("key " + eduOpenVPN.Configuration.EscapeParamValue(ConnectingProfile.Server.ClientCertificatePath));

                                // Ask when username/preplacedword is denied.
                                sw.WriteLine("auth-retry interact");
                                sw.WriteLine("auth-nocache");

                                // Set Wintun interface to be used.
                                sw.Write("windows-driver wintun\n");
                                sw.Write("dev-node " + eduOpenVPN.Configuration.EscapeParamValue(Properties.Settings.Default.Clientreplacedle) + "\n");

#if DEBUG
                                // Renegotiate data channel every 5 minutes in debug versions.
                                sw.WriteLine("reneg-sec 300");
#endif

                                if (Environment.OSVersion.Version < new Version(6, 2))
                                {
                                    // Windows 7 is using tiny 8kB send/receive socket buffers by default.
                                    // Increase to 64kB which is default from Windows 8 on.
                                    sw.WriteLine("sndbuf 65536");
                                    sw.WriteLine("rcvbuf 65536");
                                }

                                var openVPNAddOptions = Properties.SettingsEx.Default.OpenVPNAddOptions;
                                if (!string.IsNullOrWhiteSpace(openVPNAddOptions))
                                {
                                    sw.WriteLine();
                                    sw.WriteLine();
                                    sw.WriteLine("# Added by OpenVPNAddOptions setting:");
                                    sw.WriteLine(openVPNAddOptions);
                                }
                            }
                        }
                        catch (OperationCanceledException) { throw; }
                        catch (Exception ex) { throw new AggregateException(string.Format(Resources.Strings.ErrorSavingProfileConfiguration, ConfigurationPath), ex); }

                        bool retry;
                        do
                        {
                            retry = false;

                            // Connect to OpenVPN Interactive Service to launch the openvpn.exe.
                            using (var openvpnInteractiveServiceConnection = new eduOpenVPN.InteractiveService.Session())
                            {
                                var mgmtPreplacedword = Membership.GeneratePreplacedword(16, 6);
                                try
                                {
                                    openvpnInteractiveServiceConnection.Connect(
                                        string.Format("openvpn{0}\\service", InstanceName),
                                        WorkingFolder,
                                        new string[] { "--config", ConnectionId + ".conf", },
                                        mgmtPreplacedword + "\n",
                                        3000,
                                        SessionAndWindowInProgress.Token);
                                }
                                catch (OperationCanceledException) { throw; }
                                catch (Exception ex) { throw new AggregateException(Resources.Strings.ErrorInteractiveService, ex); }

                                try
                                {
                                    // Wait and accept the openvpn.exe on our management interface (--management-client parameter).
                                    var mgmtClientTask = mgmtServer.AcceptTcpClientAsync();
                                    try { mgmtClientTask.Wait(30000, SessionAndWindowInProgress.Token); }
                                    catch (AggregateException ex) { throw ex.InnerException; }
                                    var mgmtClient = mgmtClientTask.Result;
                                    try
                                    {
                                        // Start the management session.
                                        ManagementSession.Start(mgmtClient.GetStream(), mgmtPreplacedword, SessionAndWindowInProgress.Token);

                                        // Initialize session and release openvpn.exe to get started.
                                        ManagementSession.SetVersion(3, SessionAndWindowInProgress.Token);
                                        ManagementSession.ReplayAndEnableState(SessionAndWindowInProgress.Token);
                                        ManagementSession.ReplayAndEnableEcho(SessionAndWindowInProgress.Token);
                                        ManagementSession.SetByteCount(5, SessionAndWindowInProgress.Token);
                                        ManagementSession.ReleaseHold(SessionAndWindowInProgress.Token);

                                        Wizard.Dispatcher.Invoke(DispatcherPriority.Normal, (Action)(() => Wizard.TaskCount--));
                                        try
                                        {
                                            // Wait for the session to end gracefully.
                                            ManagementSession.Monitor.Join();
                                            if (ManagementSession.Error != null && !(ManagementSession.Error is OperationCanceledException))
                                            {
                                                // Session reported an error. Retry.
                                                retry = true;
                                            }
                                        }
                                        finally { Wizard.Dispatcher.Invoke(DispatcherPriority.Normal, (Action)(() => Wizard.TaskCount++)); }
                                    }
                                    finally { mgmtClient.Close(); }
                                }
                                finally
                                {
                                    Wizard.Dispatcher.Invoke(DispatcherPriority.Normal, (Action)(
                                        () =>
                                        {
                                            // Cleanup status properties.
                                            State = SessionStatusType.Disconnecting;
                                            StateDescription = Resources.Strings.OpenVPNStateTypeExiting;
                                            TunnelAddress = null;
                                            IPv6TunnelAddress = null;
                                            ConnectedAt = null;
                                            BytesIn = null;
                                            BytesOut = null;
                                        }));

                                    // Wait for openvpn.exe to finish. Maximum 30s.
                                    try { Process.GetProcessById(openvpnInteractiveServiceConnection.ProcessId)?.WaitForExit(30000); }
                                    catch (ArgumentException) { }
                                }
                            }
                        } while (retry);
                    }
                    finally
                    {
                        mgmtServer.Stop();
                    }
                }
                finally
                {
                    // Delete profile configuration file. If possible.
                    try { File.Delete(ConfigurationPath); }
                    catch { }
                }
            }
            finally
            {
                Wizard.Dispatcher.Invoke(DispatcherPriority.Normal, (Action)(
                    () =>
                    {
                        // Cleanup status properties.
                        State = SessionStatusType.Disconnected;
                        StateDescription = "";

                        Wizard.TaskCount--;
                    }));
                PropertyUpdater.Stop();
            }
        }

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

public static string ReplaceIpPlaceholder(this string text)
        {
            if (!text.Contains(LocalIp))
                return text;
            return text.Replace(LocalIp, GetLocalInternetIp().ToString());
        }

19 View Source File : FileObserver.cs
License : MIT License
Project Creator : AndreiMisiukevich

[PermissionSet(SecurityAction.Demand, Name = "FullTrust")]
        private static void Run()
        {
            var addresses = NetworkInterface.GetAllNetworkInterfaces()
                .SelectMany(x => x.GetIPProperties().UnicastAddresses)
                .Where(x => x.Address.AddressFamily == AddressFamily.InterNetwork)
                .Select(x => x.Address.MapToIPv4())
                .Where(x => x.ToString() != "127.0.0.1")
                .ToArray();

            var ip = addresses.FirstOrDefault()?.ToString() ?? "127.0.0.1";

            var args = Environment.GetCommandLineArgs();
            var path = RetrieveCommandLineArgument("p=", Environment.CurrentDirectory, args);
            var url = RetrieveCommandLineArgument("u=", $"http://{ip}:8000", args);
            var autoDiscoveryPort = RetrieveCommandLineArgument("a=", "15000", args);

            try
            {
                Directory.GetDirectories(path);
            }
            catch
            {
                Console.WriteLine("MAKE SURE YOU PreplacedED RIGHT PATH TO PROJECT DIRECTORY AS 'P={PATH}' ARGUMENT.");
                Console.ReadKey();
                return;
            }

            foreach (var addr in url.Split(new char[] { ',', ';' }))
            {
                if (!Uri.IsWellFormedUriString(addr, UriKind.Absolute))
                {
                    Console.WriteLine("MAKE SURE YOU PreplacedED RIGHT DEVICE URL AS 'U={DEVICE_URL}' OR AS 'U={DEVICE_URL,DEVICE_URL2,...}' ARGUMENT.");
                    Console.ReadKey();
                    return;
                }

                _addresses.Add(addr);
            }

            UdpReceiver receiver = null;
            try
            {
                receiver = new UdpReceiver(int.Parse(autoDiscoveryPort));
                receiver.Received += (addressMsg) =>
                {
                    //TODO: pick needed address
                    var address = addressMsg.Split(';').FirstOrDefault();
                    if (address != null)
                    {
                        if (!_addresses.Contains(address))
                        {
                            Console.WriteLine($"ADDRESS IS DETECTED: {address}");
                            _addresses.Add(address);
                        }
                    }
                };
                receiver.StartAsync();
            }
            catch
            {
                Console.WriteLine("MAKE SURE YOU PreplacedED RIGHT AUTO DISCOVERY RECEIVER PORT AS 'A={PORT}' ARGUMENT.");
                Console.ReadKey();
                return;
            }

            Console.WriteLine($"\n\n> HOTRELOADER STARTED AT {DateTime.Now}");
            Console.WriteLine($"\n> PATH: {path}");
            Console.WriteLine($"\n> AUTO DISCOVERY PORT: {autoDiscoveryPort}");

            foreach (var addr in _addresses)
            {
                Console.WriteLine($"\n> URL: {addr}\n");
            }


            _client = new HttpClient();

            foreach (var fileExtension in _supportedFileExtensions)
            {
                var observer = new FileSystemWatcher
                {
                    Path = path,
                    NotifyFilter = NotifyFilters.LastWrite |
                        NotifyFilters.Attributes |
                        NotifyFilters.Size |
                        NotifyFilters.CreationTime |
                        NotifyFilters.FileName,
                    Filter = $"*{fileExtension}",
                    EnableRaisingEvents = true,
                    IncludeSubdirectories = true
                };

                observer.Changed += OnFileChanged;
                observer.Created += OnFileChanged;
                observer.Renamed += OnFileChanged;
            }

            do
            {
                Console.WriteLine("\nPRESS \'ESC\' TO STOP.");
            } while (Console.ReadKey().Key != ConsoleKey.Escape);

            receiver.Stop();
        }

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

public async Task StartAsync(int listeningPort)
        {
            _server = new global::Grpc.Core.Server
            {
                Ports =
                {
                    new ServerPort(IPAddress.Any.ToString(), listeningPort, ServerCredentials.Insecure)
                },
                Services =
                {
                    ParentChainRpc.BindService(_grpcParentChainServerBase),
                    SideChainRpc.BindService(_grpcSideChainServerBase),
                    BasicCrossChainRpc.BindService(_grpcBasicServerBase)
                }
            };

            await Task.Run(() => _server.Start());

            Logger.LogInformation($"Grpc cross chain server started, listening at {listeningPort}");
            IsStarted = true;
        }

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

private string Connect(IPEndPoint addr)
        {
            var stringAdress = addr.Address.ToString();
            var logMsg = "Connecting to server. Addr: " + stringAdress + ":" + addr.Port.ToString();
            Loger.Log("Chat " + logMsg);

            if (!_sessionClient.Connect(stringAdress, addr.Port))
            {
                logMsg = "Connection fail: " + _sessionClient.ErrorMessage;
                return _sessionClient.ErrorMessage;
            }

            Loger.Log("Chat " + logMsg);

            return null;
        }

19 View Source File : EdisFace.cs
License : MIT License
Project Creator : 0ffffffffh

private bool IsClientPermittedForSuserAddition(HttpListenerContext ctx, bool modify)
        {
            bool allowed;
            string clientIp;
            string query;
            

            clientIp = ctx.Request.RemoteEndPoint.Address.MapToIPv4().ToString();

            if (IsClientDeniedAtThisSessionBefore(clientIp))
            {
                return false;
            }

            SqlServerIo sql = SqlServerIo.Create();

            if (!sql.Ready)
                return false;

            query = "DECLARE @Permit BIT " +
                "EXEC IsRegistrationAllowed {0}, '{1}', @Permit OUTPUT " +
                "SELECT @Permit AS IsAllowed";
            
            
            sql.Execute(false, query, modify?1:0,clientIp);

            sql.Read();

            allowed = sql.GetValueOfColumn<bool>("IsAllowed");
            
            SqlServerIo.Release(sql);

            if (!allowed)
                CacheDeniedClient(clientIp);

            return allowed;
        }

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

private void StartServer()
    {
        // Establish the local endpoint for the socket. 
        IPAddress ipAddress = ServerInfo.ipAddress;
        IPEndPoint localEndPoint = ServerInfo.localEP;

        Console.WriteLine("The server is running at: " + localEndPoint.Address.ToString() + " : " + localEndPoint.Port.ToString());
        Console.WriteLine("Is loopback: " + IPAddress.IsLoopback(localEndPoint.Address));

        // Create a TCP/IP socket.  
        listenerSocket = new Socket(ipAddress.AddressFamily,
            SocketType.Stream, ProtocolType.Tcp);

        // Bind the socket to the local endpoint and listen for incoming connections.  
        try
        {
            listenerSocket.Bind(localEndPoint);
            listenerSocket.Listen(MaximumPlayers);

            Thread selectThr = new Thread(StartListening);
            selectThr.Start();
        }
        catch (Exception e)
        {
            Debug.Log(e.ToString());
            Application.Quit();
        }
    }

19 View Source File : TLV_002D.cs
License : MIT License
Project Creator : 499116344

public static string GetLocalIP()
        {
            var localIP = "192.168.1.2";
            try
            {
                var host = Dns.GetHostEntry(Dns.GetHostName());
                foreach (var ip in host.AddressList)
                {
                    if (ip.AddressFamily.ToString() == "InterNetwork")
                    {
                        localIP = ip.ToString();
                        break;
                    }
                }
            }
            catch (Exception)
            {
                localIP = "192.168.1.2";
            }

            return localIP;
        }

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

public void Do(ConnectClient client, Action<Action<SessionServer>> allSessionAction)
        {
            try
            {
                Client = client;

                Loger.Log("Server ReceiveBytes1");

                ///установка условно защищенного соединения
                //Строго первый пакет: Передаем серверу КОткр
                var rc = Client.ReceiveBytes();
                var crypto = new CryptoProvider();
                if (SessionClient.UseCryptoKeys) crypto.OpenKey = Encoding.UTF8.GetString(rc);

                //Строго первый ответ: Передаем клиенту КОткр(Сессия)
                SetKey();
                Loger.Log("Server SendMessage1");
                if (SessionClient.UseCryptoKeys)
                    Client.SendMessage(crypto.Encrypt(Key));
                else
                    Client.SendMessage(Key);

                var context = new ServiceContext();
                context.AddrIP = ((IPEndPoint)client.Client.Client.RemoteEndPoint).Address.ToString();
                context.AllSessionAction = allSessionAction;
                Worker = new Service(context);

                ///рабочий цикл
                while (IsActive)
                {
                    var rec = Client.ReceiveBytes();
                    if (!IsActive) break;

                    if (context.Player != null)
                    {
                        lock (context.Player)
                        {
                            context.Player.Public.LastOnlineTime = DateTime.UtcNow;
                        }
                    }

                    //отдельно обрабатываем пинг
                    if (rec.Length == 1)
                    {
                        if (rec[0] == 0x00)
                        {
                            Client.SendMessage(new byte[1] { 0x00 });
                        }
                        //отдельно обрабатываем запрос на обновление (ответ 0 - нет ничего, 1 - что-то есть) 
                        else if (rec[0] == 0x01)
                        {
                            var exists = ServiceCheck();
                            Client.SendMessage(new byte[1] { exists ? (byte)0x01 : (byte)0x00 });
                        }
                        continue;
                    }

                    var time1 = DateTime.UtcNow;

                    var rec2 = CryptoProvider.SymmetricDecrypt(rec, Key);
                    var recObj = (ModelContainer)GZip.UnzipObjByte(rec2); //Deserialize

                    if (rec.Length > 1024 * 512) Loger.Log($"Server Network fromC {rec.Length} unzip {GZip.LastSizeObj} ");
                    var time2 = DateTime.UtcNow;

                    ModelContainer sendObj;
                    try
                    {
                        sendObj = Worker.GetPackage(recObj);
                        if (!IsActive) break;
                    }
                    catch (Exception ext)
                    {
                        Loger.Log("Exception GetPackage: " + ext.ToString());
                        sendObj = null;
                    }
                    if (sendObj == null)
                    {
                        sendObj = new ModelContainer()
                        {
                            TypePacket = 0
                        };
                    }

                    var time3 = DateTime.UtcNow;

                    var ob = GZip.ZipObjByte(sendObj); //Serialize
                    var send = CryptoProvider.SymmetricEncrypt(ob, Key);

                    if (send.Length > 1024 * 512) Loger.Log($"Server Network toC {send.Length} unzip {GZip.LastSizeObj} ");
                    var time4 = DateTime.UtcNow;

                    Client.SendMessage(send);

                    var time5 = DateTime.UtcNow;

                    if ((time5 - time1).TotalMilliseconds > 900)
                    {
                        Loger.Log($"Server Network timeDeserialize {(time2 - time1).TotalMilliseconds}" +
                            $" timeWorker {(time3 - time2).TotalMilliseconds}" +
                            $" timeSerialize {(time4 - time3).TotalMilliseconds}" +
                            $" timeSend {(time5 - time4).TotalMilliseconds}");
                    }

                    if (context.Player != null)
                    {
                        lock (context.Player)
                        {
                            context.Player.Public.LastOnlineTime = DateTime.UtcNow;
                            if (context.Player.ExitReason != OCUnion.Transfer.DisconnectReason.AllGood)
                            {
                                //context.Player.ExitReason = OCUnion.Transfer.DisconnectReason.AllGood;
                                Loger.Log("Disconnect  . . ." + context.Player.ExitReason.ToString());
                                break;
                            }
                        }
                    }
                }
            }
            finally
            {
                IsActive = false;
            }
        }

19 View Source File : NetUtility.cs
License : MIT License
Project Creator : Aircoookie

public static bool IsConnectedToWledAP()
        {
            /*var host = Dns.GetHostEntry(Dns.GetHostName());
            foreach (var ip in host.AddressList)
            {
                if (ip.AddressFamily == AddressFamily.InterNetwork)
                {
                    string ips = ip.ToString();
                    
                    if (ips.StartsWith("192.168.4."))
                    {
                        int dev = 0;
                        if (!Int32.TryParse(ips.Substring(10), out dev)) { dev = 0; }
                        if (dev > 1 && dev < 6) return true;
                    }
                }
            }
            return false;*/

            foreach (var netInterface in NetworkInterface.GetAllNetworkInterfaces())
            {
                if (netInterface.NetworkInterfaceType == NetworkInterfaceType.Wireless80211 ||
                    netInterface.NetworkInterfaceType == NetworkInterfaceType.Ethernet)
                {
                    foreach (var addrInfo in netInterface.GetIPProperties().UnicastAddresses)
                    {
                        if (addrInfo.Address.AddressFamily == AddressFamily.InterNetwork)
                        {
                            var ip = addrInfo.Address;
                            string ips = ip.ToString();

                            if (ips.StartsWith("192.168.4."))
                            {
                                int dev = 0;
                                if (!Int32.TryParse(ips.Substring(10), out dev)) { dev = 0; }
                                if (dev > 1 && dev < 6) return true;
                            }
                        }
                    }
                }
            }

            return false;
        }

See More Examples