protected int ParseTrustIPString(string value) { if (string.IsNullOrEmpty(value)) return 0; if (TrustRemoteIP != null) { TrustRemoteIP.Clear(); TrustRemoteIP = null; } try { string[] ips = value.Split(new char[] { ';', ',' }); if (ips != null && ips.Length > 0) { TrustRemoteIP = new HashSet<long>(); foreach (string ipAddr in ips) { long ip = IPUtility.GetIPIntValue(ipAddr); TrustRemoteIP.Add(ip); } } } catch { } return TrustRemoteIP != null ? TrustRemoteIP.Count : 0; }
protected virtual bool RegistTrustIP(ClientManager clmngr) { if (clmngr == null) { return(false); } string ipAddr = ((IPEndPoint)clmngr.Socket.RemoteEndPoint).Address.ToString(); long remoteIP = IPUtility.GetIPIntValue(ipAddr); try { if (remoteIP == _LocalhostIP) { return(false); } if (_Config.TrustRemoteIP != null && _Config.TrustRemoteIP.Count > 0) { foreach (long ip in _Config.TrustRemoteIP) { if (ip == remoteIP) { clmngr.IsTrustIP = true; break; } } } } catch { } return(clmngr.IsTrustIP); }
static void Main(string[] args) { var proxy = ClientProxyFactory.Create() .UseCastleDynamicClientProxy() .UseJsonNetSerializer() .UseDefaultChannel($"{IPUtility.GetLocalIntranetIP().MapToIPv4()}:5566") .GetClientProxy(); var mathService = proxy.Create <IMathService>(); var random = new Random(); var req = new SumReq { A = random.Next(100000), B = random.Next(100000) }; var result = mathService.SumAsync(req).GetAwaiter().GetResult(); if (result.Code == 0) { Console.WriteLine("Call Math Service Add {0}+{1}={2}", req.A, req.B, result.Data?.Total); } else { Console.WriteLine("Call Math Service Error,Code={0}", result.Code); } Console.WriteLine("Press any key to exit !"); Console.ReadKey(); }
public string GetIP() { if (_ipUtility == null) { _ipUtility = new IPUtility(); } return(_ipUtility.GetIPAndCity()); }
public void Start() { isRunning = true; systemSocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); systemSocket.Bind(IPUtility.GetIPEndPointAny(AddressFamily.InterNetwork, port)); threadRecv = new Thread(ThreadRecv) { IsBackground = true }; threadRecv.Start(); }
private void DoReceiveInThread() { EndPoint remotePoint = IPUtility.GetIPEndPointAny(AddressFamily.InterNetwork, 0); int cnt = currentSocket.ReceiveFrom(byteBuffer, byteBuffer.Length, SocketFlags.None, ref remotePoint); if (cnt > 0) { byte[] dst = new byte[cnt]; Buffer.BlockCopy(byteBuffer, 0, dst, 0, cnt); lock (recvBufferQueue) { recvBufferQueue.Enqueue(dst); } } }
public void Start() { try { currentSocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); currentSocket.Bind(IPUtility.GetIPEndPointAny(AddressFamily.InterNetwork, ipcInfo.Port)); isRunning = true; threadRecv = new Thread(ThreadRecv) { IsBackground = true }; threadRecv.Start(); } catch (Exception e) { Debuger.LogError(e.Message + e.StackTrace); Stop(); } }
private void DoReceiveInThread() { EndPoint remotePoint = IPUtility.GetIPEndPointAny(AddressFamily.InterNetwork, 0); int cnt = currentSocket.ReceiveFrom(recvBufferTemp, recvBufferTemp.Length, SocketFlags.None, ref remotePoint); if (cnt > 0) { if (!remoteEndPoint.Equals(remotePoint)) { Debuger.LogError("收到非目标服务器的数据!"); return; } byte[] dst = new byte[cnt]; Buffer.BlockCopy(recvBufferTemp, 0, dst, 0, cnt); recvBuffQueue.Push(dst); } }
static void Main(string[] args) { /* default route */ var factory = ClientProxyFactory.Create() .UseCastleDynamicClientProxy() .ConfigureLogging(logger => logger.AddConsole()) .UseMessagePackSerializer() .UseDefaultChannel($"{IPUtility.GetLocalIntranetIP().MapToIPv4()}:5566"); /* service discovery route * var factory = ClientProxyFactory.Create() * .ConfigureLogging(logger =>logger.AddConsole()) * .UseCastleDynamicProxy() * .UseMessagePackSerializer() * .UseConsulDnsServiceDiscovery(); //默认配置 localhost */ var proxy = factory.GetProxyInstance(); var mathService = proxy.Create <IMathService>(); var i = 0; var random = new Random(); while (i++ < 100) { var req = new SumReq { A = random.Next(100000), B = random.Next(100000) }; var result = mathService.SumAsync(req).Result; Console.WriteLine("Call Math Service ,return_code={0}", result.Code); if (result.Code == 0) { Console.WriteLine("Call Math Service Add {0}+{1}={2}", req.A, req.B, result.Data?.Total); } Console.WriteLine("============= count:{0}", i); } Console.WriteLine("Press any key to exit !"); Console.ReadKey(); }
public void Add_A_Status_Test() { // Arrange var text = "▓Р╩ниб╦═╬б▓Е " + DateTime.Now.ToLongTimeString(); var request = new QQStatusAddRequest(text) { ClientIp = IPUtility.GetFirstLocalIP() }; // Act var response = WeiboClient.Post(request); // Assert Assert.IsNotNull(response); Assert.AreEqual("0", response.Ret); Console.WriteLine(response.Id); Console.WriteLine(response.Timestamp); }
public void Connect(string ip, int port) { Debuger.Log("连接服务端 IP {0} Port {1} ", ip, port); IP = ip; remoteIp = ip; remotePort = port; remotEndPoint = IPUtility.GetHostEndPoint(ip, port); currentSocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); currentSocket.Bind(new IPEndPoint(IPAddress.Any, Port)); kcp = new KCP(0, HandleKcpSend); kcp.NoDelay(1, 10, 2, 1); kcp.WndSize(128, 128); Connected = true; threadRecv = new Thread(ThreadRecv) { IsBackground = true }; threadRecv.Start(); }
private static void Main(string[] args) { var proxy = ClientProxyFactory.Create() .UseCastleDynamicClientProxy() .UseMessagePackSerializer() .UseDefaultChannel($"{IPUtility.GetLocalIntranetIP().MapToIPv4()}:5566") .GetClientProxy(); var service = proxy.Create <IQuickStartService>(); // 项目中应保证异步到底的调用 var res = service.SayHelloAsync(new SayHelloReq { Name = "Maxi" }).GetAwaiter().GetResult(); Console.WriteLine(res?.Data?.GreetingWords); Console.WriteLine("Press any key to exit !"); Console.ReadKey(); }
public void Add_A_Comment_Test() { // Arrange var text = "²âÊÔ·¢ÆÀÂÛ " + DateTime.Now.ToLongTimeString(); var reid = "47032096626287"; var request = new QQCommentAddRequest(reid, text) { ClientIp = IPUtility.GetFirstLocalIP() }; // Act var response = WeiboClient.Post(request); // Assert Assert.IsNotNull(response); Assert.AreEqual("0", response.Ret); Console.WriteLine(response.Id); Console.WriteLine(response.Timestamp); }
public void Connect(string ip, int port) { IP = ip; remoteIp = ip; remotePort = port; Connected = true; remotEndPoint = IPUtility.GetHostEndPoint(ip, port); try { currentSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); currentSocket.Bind(new IPEndPoint(IPAddress.Any, Port)); currentSocket.Connect(ip, port); currentSocket.BeginReceive(cacheBuffer, 0, cacheBuffer.Length, SocketFlags.None, ReceiveCallBack, cacheBuffer); } catch (Exception e) { Debuger.LogError(e); } }
private void DoReceiveInThread() { EndPoint remotePoint = IPUtility.GetIPEndPointAny(AddressFamily.InterNetwork, 0); int cnt = currentSocket.ReceiveFrom(byteBuffer, byteBuffer.Length, SocketFlags.None, ref remotePoint); if (cnt > 0) { recvBufferTempReader.Attach(byteBuffer, cnt); byte[] convBytes = new byte[4]; recvBufferTempReader.ReadBytes(convBytes, 0, 4); uint sessionid = BitConverter.ToUInt32(convBytes, 0); lock (sessions) { ISession session = null; if (sessionid == 0) { sessionid = SessionIDGenerator.GetNextSessionID(); session = new KCPSession(sessionid, HandleSessionSend, sessionListener); sessions.Add(session.id, session); } else { if (sessions.ContainsKey(sessionid)) { session = sessions[sessionid]; } } if (session != null) { session.Active(remotePoint as IPEndPoint); session.DoReceiveInGateway(byteBuffer, cnt); } else { Debuger.LogWarning("无效的包! sessionid:{0}", sessionid); } } } }
static void Main(string[] args) { /* * TcpClientOption option = new TcpClientOption { * Certificate = Path.Combine(AppContext.BaseDirectory, "../../../../../shared/dotnetty.com.pfx"), * CertificatePassword = "******" * }; */ //实例化Client 需要传入使用的协议 //TcpClient<CommandLineMessage> client = new TcpClient<CommandLineMessage>(option,new CommandLineChannelHandlerPipeline()); TcpClient <CommandLineMessage> client = new TcpClient <CommandLineMessage>(new CommandLineChannelHandlerPipeline()); client.OnReceived += Client_OnReceived; client.OnConnected += Client_OnConnected; client.OnIdleState += Client_OnIdleState; client.OnDisconnected += Client_OnDisconnected; client.OnError += Client_OnError; Task.Run(async() => { //连接服务器,可以链接多个哦 var socketContext = await client.ConnectAsync(new IPEndPoint(IPUtility.GetLocalIntranetIP(), 5566)); //发送消息 Console.WriteLine("send msg init"); var initCmd = new CommandLineMessage("init"); await socketContext.SendAsync(initCmd); Console.WriteLine("send msg echo hello"); //发送消息2 var echoCmd = new CommandLineMessage("echo", "hello"); await socketContext.SendAsync(echoCmd); Console.WriteLine("Press any key to exit!"); Console.ReadKey(); //关闭链接 await client.ShutdownGracefullyAsync(2000, 2000); }).Wait(); }
private void DoReceiveInThread() { EndPoint remotePoint = IPUtility.GetIPEndPointAny(AddressFamily.InterNetwork, 0); int cnt = systemSocket.ReceiveFrom(recvBufferTemp, recvBufferTemp.Length, SocketFlags.None, ref remotePoint); if (cnt > 0) { recvBufferTempReader.Attach(recvBufferTemp, cnt); byte[] m_32b = new byte[4]; recvBufferTempReader.ReadBytes(m_32b, 0, 4); uint sid = BitConverter.ToUInt32(m_32b, 0); lock (mapSession) { FSPSession session = null; if (sid == 0) { Debuger.LogError("基于KCP的Sid为0,该包需要被丢掉"); } else { if (mapSession.ContainsKey(sid)) { session = mapSession[sid]; } } if (session != null) { session.Active(remotePoint as IPEndPoint); session.DoReceiveInGateway(recvBufferTemp, cnt); } else { Debuger.LogWarning("无效的包! sid:{0}", sid); } } } }
public bool Connect(string ipAddress, int listenPort) { if (currentSocket != null) { Debuger.LogError("无法建立连接,需要先关闭上一次连接!"); return(false); } ip = ipAddress; port = listenPort; lastRecvTimestamp = (uint)TimeUtility.GetTotalMillisecondsSince1970(); try { remoteEndPoint = IPUtility.GetHostEndPoint(ip, port); if (remoteEndPoint == null) { Debuger.LogError("无法将Host解析为IP!"); Close(); return(false); } currentSocket = new Socket(remoteEndPoint.AddressFamily, SocketType.Dgram, ProtocolType.Udp); currentSocket.Bind(IPUtility.GetIPEndPointAny(AddressFamily.InterNetwork, 0)); isRunning = true; threadRecv = new Thread(ThreadRecv) { IsBackground = true }; threadRecv.Start(); } catch (Exception e) { Debuger.LogError(e.Message + e.StackTrace); Close(); return(false); } return(true); }
static void Main(string[] args) { /* * TcpClientOption option = new TcpClientOption { * Certificate = Path.Combine(AppContext.BaseDirectory, "../../../../../shared/dotnetty.com.pfx"), * CertificatePassword = "******" * }; */ //实例化Client 需要传入使用的协议 //TcpClient<CommandLineMessage> client = new TcpClient<CommandLineMessage>(option,new CommandLineChannelHandlerPipeline()); TcpClient <MqttMessage> client = new TcpClient <MqttMessage>(new MqttChannelHandlerPipeline(new MqttOptions())); client.OnReceived += Client_OnReceived; client.OnConnected += Client_OnConnected; Task.Run(async() => { //连接服务器,可以链接多个哦 var socketContext = await client.ConnectAsync(new IPEndPoint(IPUtility.GetLocalIntranetIP(), 5566)); //发送消息 var connPack = new ConnectPacket { ClientId = Guid.NewGuid().ToString("N") }; await socketContext.SendAsync(new MqttMessage { Packet = connPack }); Console.WriteLine("Press any key to exit!"); Console.ReadKey(); //关闭链接 await client.ShutdownGracefullyAsync(2000, 2000); }).Wait(); }
private void SendMessage(int dstID, byte[] bytes, int len) { int dstPort = IPCConfig.GetIPCInfo(dstID).Port; IPEndPoint ep = IPUtility.GetHostEndPoint("127.0.0.1", dstPort); currentSocket.SendTo(bytes, 0, len, SocketFlags.None, ep); }
/// <summary> /// new /// </summary> /// <param name="serviceType"></param> /// <param name="zkConfigPath"></param> /// <param name="zkConfigName"></param> /// <param name="zNode"></param> /// <param name="callback"></param> public ZoomkeeperDiscovery(string serviceType, string zkConfigPath, string zkConfigName, string zNode, Action <IPEndPoint[]> callback) { if (string.IsNullOrEmpty(serviceType)) { throw new ArgumentNullException("serviceType"); } if (string.IsNullOrEmpty(zkConfigPath)) { throw new ArgumentNullException("zkConfigPath"); } if (string.IsNullOrEmpty(zkConfigName)) { throw new ArgumentNullException("zkConfigName"); } if (string.IsNullOrEmpty(zNode)) { throw new ArgumentNullException("zNode"); } if (callback == null) { throw new ArgumentNullException("callback"); } this._callback = callback; this._zk = ZookClientPool.Get(zkConfigPath, "zookeeper", zkConfigName); this.RegisterZNode(new NodeInfo[] { new NodeInfo(string.Concat("/", zNode), null, IDs.OPEN_ACL_UNSAFE, CreateModes.Persistent), new NodeInfo(string.Concat("/", zNode, "/consumers"), null, IDs.OPEN_ACL_UNSAFE, CreateModes.Persistent) }); this._sessionNode = new SessionNode(this._zk, string.Concat("/", zNode, "/consumers/", Uri.EscapeDataString(string.Format( @"consumer://{0}/{1}?application={2}&category=consumers&check=false&dubbo=2.5.1& interface={1}&methods={6}&owner={3}&pid={4}&revision=0.0.2-SNAPSHOT& side=consumer×tamp={5}", IPUtility.GetLocalIntranetIP().ToString(), zNode, Process.GetCurrentProcess().ProcessName, string.Empty, Process.GetCurrentProcess().Id.ToString(), Date.ToMillisecondsSinceEpoch(DateTime.UtcNow).ToString(), string.Join(",", Type.GetType(serviceType).GetInterfaces()[0].GetMethods().Select(c => c.Name).ToArray())))), null, IDs.OPEN_ACL_UNSAFE); this._watcher = new ChildrenWatcher(this._zk, string.Concat("/", zNode, "/providers"), arrNodes => { this._callback(arrNodes.Select(c => { var objUri = new Uri(Uri.UnescapeDataString(c)); return(new IPEndPoint(IPAddress.Parse(objUri.Host), objUri.Port)); }).ToArray()); //lock (this._lockObj) //{ // var arrExists = this._thrift.GetAllRegisteredEndPoint().Select(c => c.Key).Distinct().ToArray(); // var arrCurr = arrNodes.Select(node => // { // var strUrl = Uri.UnescapeDataString(node); // strUrl = strUrl.Substring(strUrl.IndexOf(":") + 3); // return strUrl.Substring(0, strUrl.IndexOf("/")); // }).ToArray(); // var set = new HashSet<string>(arrExists); // set.ExceptWith(arrCurr); // if (set.Count > 0) // { // foreach (var child in set) // this._thrift.UnRegisterEndPoint(child); // } // set = new HashSet<string>(arrCurr); // set.ExceptWith(arrExists); // if (set.Count > 0) // { // foreach (var child in set) // { // var i = child.IndexOf(":"); // var endpoint = new IPEndPoint(IPAddress.Parse(child.Substring(0, i)), int.Parse(child.Substring(i + 1))); // this._thrift.TryRegisterEndPoint(child, new EndPoint[] { endpoint }); // } // } //} }); }
public async Task StartAsync(CancellationToken cancellationToken) { if (!RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) { System.Runtime.GCSettings.LatencyMode = System.Runtime.GCLatencyMode.SustainedLowLatency; } //if (_options.UseLibuv) //{ // var dispatcher = new DispatcherEventLoopGroup(); // _bossGroup = dispatcher; // _workerGroup = new WorkerEventLoopGroup(dispatcher); //} //else { // 主的线程 _bossGroup = new MultithreadEventLoopGroup(1); // 工作线程,默认根据CPU计算 _workerGroup = new MultithreadEventLoopGroup(); } var bootstrap = new ServerBootstrap() .Group(_bossGroup, _workerGroup); //if (_options.UseLibuv) { //bootstrap.Channel<TcpServerChannel>(); } //else { bootstrap.Channel <TcpServerSocketChannel>(); } bootstrap.Option(ChannelOption.SoBacklog, _options.SoBacklog); //NOTE: 是否可以公开更多Netty的参数 if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux) || RuntimeInformation.IsOSPlatform(OSPlatform.OSX)) { bootstrap .Option(ChannelOption.SoReuseport, true) .ChildOption(ChannelOption.SoReuseaddr, true); } X509Certificate2 tlsCertificate = null; if (!string.IsNullOrEmpty(_options.Certificate)) { tlsCertificate = new X509Certificate2(_options.Certificate, _options.CertificatePassword); } _ = bootstrap.Handler(new LoggingHandler("LSTN")) .ChildHandler(new ActionChannelInitializer <ISocketChannel>(channel => { var pipeline = channel.Pipeline; if (tlsCertificate != null) { pipeline.AddLast("tls", TlsHandler.Server(tlsCertificate)); } pipeline.AddLast(new LoggingHandler("CONN")); foreach (var kv in _handlerPipeline.BuildPipeline(true)) { pipeline.AddLast(kv.Key, kv.Value); } //业务处理Handler,即解码成功后如何处理消息的类 pipeline.AddLast(new TcpServerChannelHandlerAdapter <TMessage>(_socketService)); })); if (_options.BindType == AddressBindType.Any) { _channel = await bootstrap.BindAsync(_options.Port); } else if (_options.BindType == AddressBindType.InternalAddress) { var localPoint = IPUtility.GetLocalIntranetIP(); if (localPoint == null) { this._logger.LogWarning("there isn't an avaliable internal ip address,the service will be hosted at loopback address."); _channel = await bootstrap.BindAsync(IPAddress.Loopback, _options.Port); } else { //this._logger.LogInformation("TcpServerHost bind at {0}",localPoint); _channel = await bootstrap.BindAsync(localPoint, this._options.Port); } } else if (_options.BindType == AddressBindType.Loopback) { _channel = await bootstrap.BindAsync(IPAddress.Loopback, _options.Port); } else { _channel = await bootstrap.BindAsync(IPAddress.Parse(_options.SpecialAddress), _options.Port); } Console.Write(_options.StartupWords, _channel.LocalAddress); }
/// <summary> /// new /// </summary> /// <param name="port"></param> /// <param name="serviceType"></param> /// <param name="zkConfigPath"></param> /// <param name="zkConfigName"></param> /// <param name="zNode"></param> /// <param name="owner"></param> public ZookeeperRegistry(int port, string serviceType, string zkConfigPath, string zkConfigName, string zNode, string owner) { if (string.IsNullOrEmpty(serviceType)) { throw new ArgumentNullException("serviceType"); } if (string.IsNullOrEmpty(zkConfigPath)) { throw new ArgumentNullException("zkConfigPath"); } if (string.IsNullOrEmpty(zkConfigName)) { throw new ArgumentNullException("zkConfigName"); } if (string.IsNullOrEmpty(zNode)) { throw new ArgumentNullException("zNode"); } this._zk = ZookClientPool.Get(zkConfigPath, "zookeeper", zkConfigName); this.RegisterZNode(new NodeInfo[] { new NodeInfo(string.Concat("/", zNode), null, IDs.OPEN_ACL_UNSAFE, CreateModes.Persistent), new NodeInfo(string.Concat("/", zNode, "/providers"), null, IDs.OPEN_ACL_UNSAFE, CreateModes.Persistent) }); this._sessionNode = new SessionNode(this._zk, string.Concat("/", zNode, "/providers/", Uri.EscapeDataString(string.Format( @"thrift2://{0}:{1}/{2}?anyhost=true&application={3}&dispatcher=message&dubbo=2.5.1& interface={2}&loadbalance=roundrobin&methods={7}&owner={4}&pid={5}&revision=0.0.2-SNAPSHOT& side=provider&threads=100×tamp={6}", IPUtility.GetLocalIntranetIP().ToString(), port.ToString(), zNode, Process.GetCurrentProcess().ProcessName, owner ?? "", Process.GetCurrentProcess().Id.ToString(), Date.ToMillisecondsSinceEpoch(DateTime.UtcNow).ToString(), string.Join(",", Type.GetType(serviceType).GetInterfaces()[0].GetMethods().Select(c => c.Name).ToArray())))), null, IDs.OPEN_ACL_UNSAFE); }
public async Task StartAsync(CancellationToken cancellationToken) { // 主的线程 this._bossGroup = new MultithreadEventLoopGroup(1); // 工作线程,默认根据CPU计算 this._workerGroup = new MultithreadEventLoopGroup(); var bootstrap = new ServerBootstrap() .Group(this._bossGroup, this._workerGroup); if (this._options.UseLibuv) { bootstrap.Channel <TcpServerChannel>(); } else { bootstrap.Channel <TcpServerSocketChannel>(); } bootstrap.Channel <TcpServerSocketChannel>() .Option(ChannelOption.SoBacklog, this._options.SoBacklog); //NOTE: 是否可以公开更多Netty的参数 if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux) || RuntimeInformation.IsOSPlatform(OSPlatform.OSX)) { bootstrap .Option(ChannelOption.SoReuseport, true) .ChildOption(ChannelOption.SoReuseaddr, true); } bootstrap.Handler(new LoggingHandler("LSTN")) .ChildHandler(new ActionChannelInitializer <ISocketChannel>(channel => { var pipeline = channel.Pipeline; //TODO:ssl support pipeline.AddLast(new LoggingHandler("CONN")); var meta = this._protocol.GetProtocolMeta(); if (meta != null) { // IdleStateHandler pipeline.AddLast("timeout", new IdleStateHandler(0, 0, meta.HeartbeatInterval / 1000 * 2)); //服务端双倍来处理 //消息前处理 pipeline.AddLast( new LengthFieldBasedFrameDecoder( meta.MaxFrameLength, meta.LengthFieldOffset, meta.LengthFieldLength, meta.LengthAdjustment, meta.InitialBytesToStrip ) ); } else //Simple Protocol For Test { pipeline.AddLast("timeout", new IdleStateHandler(0, 0, 360)); // heartbeat each 6 second pipeline.AddLast("framing-enc", new LengthFieldPrepender(2)); pipeline.AddLast("framing-dec", new LengthFieldBasedFrameDecoder(ushort.MaxValue, 0, 2, 0, 2)); } //收到消息后的解码处理Handler pipeline.AddLast(new ChannelDecodeHandler <TMessage>(this._protocol)); //业务处理Handler,即解码成功后如何处理消息的类 pipeline.AddLast(new TcpServerChannelHandlerAdapter <TMessage>(this._socketService, this._protocol)); })); if (this._options.BindType == AddressBindType.Any) { this._channel = await bootstrap.BindAsync(this._options.Port); } else if (this._options.BindType == AddressBindType.InternalAddress) { var localPoint = IPUtility.GetLocalIntranetIP(); //this._logger.LogInformation("TcpServerHost bind at {0}",localPoint); this._channel = await bootstrap.BindAsync(localPoint, this._options.Port); } else if (this._options.BindType == AddressBindType.Loopback) { this._channel = await bootstrap.BindAsync(IPAddress.Loopback, this._options.Port); } else { this._channel = await bootstrap.BindAsync(IPAddress.Parse(this._options.SpecialAddress), this._options.Port); } Console.Write(this._options.StartupWords, this._channel.LocalAddress); }
private void btnIPtoLong_Click(object sender, EventArgs e) { txt02.Text = IPUtility.StringToLong(txt01.Text, chkBigEndian.Checked).ToString(); }
private IEnumerator GetLocation() { string ip = useOverrideIP ? overrideIP : IPUtility.GetIP(IpVersion.IPv6); WWW locationRequest = new WWW(geoPluginUrl + ip); yield return(locationRequest); if (locationRequest.error == null) { string locationJson = locationRequest.text; if (!string.IsNullOrEmpty(locationJson)) { string[] lines = locationJson.Split(new string[] { Environment.NewLine, "," }, StringSplitOptions.None); for (int i = 0; i < lines.Length; i++) { if (lines[i].Contains(countryCodeKey)) { if (IsNullOrEmpty(CurrentCountryCode)) { CurrentCountryCode = GetValueWithKey(lines[i], countryCodeKey); } } else if (lines[i].Contains(countryNameKey)) { if (IsNullOrEmpty(CurrentCountryName)) { CurrentCountryName = GetValueWithKey(lines[i], countryNameKey); } } else if (lines[i].Contains(cityNameKey)) { if (IsNullOrEmpty(CurrentCityName)) { CurrentCityName = GetValueWithKey(lines[i], cityNameKey); } } else if (lines[i].Contains(timeZoneKey)) { if (IsNullOrEmpty(CurrentCityName)) { CurrentCityName = GetValueWithKey(lines[i], timeZoneKey); } } } } } else { Debug.Log(locationRequest.error); } if (IsNullOrEmpty(CurrentCountryCode)) { var systemCountryCode = Application.systemLanguage.ToCountryCode(); if (!IsNullOrEmpty(systemCountryCode)) { CurrentCountryCode = systemCountryCode; } else { CurrentCountryCode = fallbackCountryCode; } } if (IsNullOrEmpty(CurrentCountryName)) { CurrentCountryName = fallbackCountryName; } if (IsNullOrEmpty(CurrentCityName)) { CurrentCityName = fallbackCityName; } Debug.Log("Country code: " + CurrentCountryCode + " | Country: " + CurrentCountryName + " | City: " + CurrentCityName); yield return(StartCoroutine(GetWeather(CurrentCountryName, CurrentCityName))); yield return(StartCoroutine(GetFlag(CurrentCountryCode))); }
private void btnLongToIP_Click(object sender, EventArgs e) { txt01.Text = IPUtility.LongToString(Convert.ToInt64(txt02.Text), chkBigEndian.Checked); }