/// <summary> /// Starts accepting new connections. /// </summary> /// <param name="address">Listening interface default: 0.0.0.0 (all)</param> /// <param name="port">Listening port default: 2000</param> public new void StartAccept(string address = "0.0.0.0", int port = 2000) { base.StartAccept(address, port); // Update window title. ConsoleTitleBuilder.IP = LocalAddress.ToString(); ConsoleTitleBuilder.Port = port; }
public static bool IsLocalAddress(string Address) { if (Address.Equals("127.0.0.1")) { return(true); } var Host = Dns.GetHostEntry(Dns.GetHostName()); foreach (var LocalAddress in Host.AddressList) { if (LocalAddress.AddressFamily == AddressFamily.InterNetwork && LocalAddress.ToString().Equals(Address)) { return(true); } } return(false); }
/// <summary> /// Determines whether the specified <see cref="T:System.Object"/> is equal to the current <see cref="T:System.Object"/>. /// </summary> /// <returns> /// true if the specified <see cref="T:System.Object"/> is equal to the current <see cref="T:System.Object"/>; otherwise, false. /// </returns> /// <param name="obj">The object to compare with the current object. </param><filterpriority>2</filterpriority> public override bool Equals(object obj) { if (obj == null) { return(false); } var passedObject = obj as TCPActivityLog; if (passedObject == null) { return(false); } if (passedObject.LocalAddress.ToString() == LocalAddress.ToString() && passedObject.RemoteEndPoint.ToString() == RemoteEndPoint.ToString()) { return(true); } else { return(false); } }
private void ServiceRetrieved(ServiceDescriptionDocument Scpd, IPEndPoint LocalEndPoint) { try { Dictionary <ushort, bool> TcpPortMapped = new Dictionary <ushort, bool>(); Dictionary <ushort, bool> UdpPortMapped = new Dictionary <ushort, bool>(); ushort PortMappingIndex; bool TcpAlreadyRegistered = false; bool UdpAlreadyRegistered = false; this.serviceWANIPConnectionV1 = new WANIPConnectionV1(Scpd); this.State = PeerToPeerNetworkState.RegisteringApplicationInGateway; this.serviceWANIPConnectionV1.GetExternalIPAddress(out string NewExternalIPAddress); this.externalAddress = IPAddress.Parse(NewExternalIPAddress); if (!IsPublicAddress(this.externalAddress)) { return; // TODO: Handle multiple layers of gateways. } PortMappingIndex = 0; try { while (true) { this.serviceWANIPConnectionV1.GetGenericPortMappingEntry(PortMappingIndex, out string NewRemoteHost, out ushort NewExternalPort, out string NewProtocol, out ushort NewInternalPort, out string NewInternalClient, out bool NewEnabled, out string NewPortMappingDescription, out uint NewLeaseDuration); if (NewPortMappingDescription == this.applicationName && NewInternalClient == LocalEndPoint.Address.ToString()) { if (NewExternalPort == this.desiredExternalPort && this.desiredExternalPort != 0) { if (NewProtocol == "TCP") { TcpAlreadyRegistered = true; PortMappingIndex++; continue; } else if (NewProtocol == "UDP") { UdpAlreadyRegistered = true; PortMappingIndex++; continue; } } this.serviceWANIPConnectionV1.DeletePortMapping(NewRemoteHost, NewExternalPort, NewProtocol); } else { switch (NewProtocol) { case "TCP": TcpPortMapped[NewExternalPort] = true; break; case "UDP": UdpPortMapped[NewExternalPort] = true; break; } PortMappingIndex++; } } } catch (AggregateException ex) { if (!(ex.InnerException is UPnPException)) { throw; } } catch (UPnPException) { // No more entries. } this.localAddress = LocalEndPoint.Address; ushort LocalPort, ExternalPort; int i; do { this.tcpListener = new TcpListener(this.localAddress, this.desiredLocalPort); this.tcpListener.Start(this.backlog); i = ((IPEndPoint)this.tcpListener.LocalEndpoint).Port; LocalPort = (ushort)(i); ExternalPort = this.desiredExternalPort == 0 ? LocalPort : (ushort)this.desiredExternalPort; if (i < 0 || i > ushort.MaxValue || TcpPortMapped.ContainsKey(ExternalPort) || UdpPortMapped.ContainsKey(ExternalPort)) { this.tcpListener.Stop(); this.tcpListener = null; throw new ArgumentException("Port already assigned to another application in the network.", nameof(ExternalPort)); } else { try { this.udpClient = new UdpClient(this.tcpListener.LocalEndpoint.AddressFamily); this.udpClient.Client.Bind((IPEndPoint)this.tcpListener.LocalEndpoint); } catch (Exception) { this.tcpListener.Stop(); this.tcpListener = null; } } }while (this.tcpListener == null); this.localEndpoint = new IPEndPoint(this.localAddress, LocalPort); if (!TcpAlreadyRegistered) { this.serviceWANIPConnectionV1.AddPortMapping(string.Empty, ExternalPort, "TCP", LocalPort, LocalAddress.ToString(), true, this.applicationName, 0); } this.tcpMappingAdded = true; if (!UdpAlreadyRegistered) { this.serviceWANIPConnectionV1.AddPortMapping(string.Empty, ExternalPort, "UDP", LocalPort, LocalAddress.ToString(), true, this.applicationName, 0); } this.udpMappingAdded = true; this.externalEndpoint = new IPEndPoint(this.externalAddress, ExternalPort); this.State = PeerToPeerNetworkState.Ready; this.AcceptTcpClients(); this.BeginReceiveUdp(); } catch (Exception ex) { this.exception = ex; this.State = PeerToPeerNetworkState.Error; } }
private void ServiceRetrieved(object Sender, ServiceDescriptionEventArgs e) { try { DeviceLocationEventArgs e2 = (DeviceLocationEventArgs)e.State; Dictionary <ushort, bool> TcpPortMapped = new Dictionary <ushort, bool>(); Dictionary <ushort, bool> UdpPortMapped = new Dictionary <ushort, bool>(); ushort PortMappingIndex; this.serviceWANIPConnectionV1 = new WANIPConnectionV1(e.ServiceDescriptionDocument); this.State = PeerToPeerNetworkState.RegisteringApplicationInGateway; this.serviceWANIPConnectionV1.GetExternalIPAddress(out string NewExternalIPAddress); this.externalAddress = IPAddress.Parse(NewExternalIPAddress); PortMappingIndex = 0; try { while (true) { this.serviceWANIPConnectionV1.GetGenericPortMappingEntry(PortMappingIndex, out string NewRemoteHost, out ushort NewExternalPort, out string NewProtocol, out ushort NewInternalPort, out string NewInternalClient, out bool NewEnabled, out string NewPortMappingDescription, out uint NewLeaseDuration); if (NewPortMappingDescription == this.applicationName && NewInternalClient == e2.LocalEndPoint.Address.ToString()) { this.serviceWANIPConnectionV1.DeletePortMapping(NewRemoteHost, NewExternalPort, NewProtocol); } else { switch (NewProtocol) { case "TCP": TcpPortMapped[NewExternalPort] = true; break; case "UDP": UdpPortMapped[NewExternalPort] = true; break; } PortMappingIndex++; } } } catch (UPnPException) { // No more entries. } this.localAddress = e2.LocalEndPoint.Address; ushort LocalPort; int i; do { this.tcpListener = new TcpListener(this.localAddress, this.desiredPort); this.tcpListener.Start(this.backlog); i = ((IPEndPoint)this.tcpListener.LocalEndpoint).Port; LocalPort = (ushort)(i); if (i < 0 || i > ushort.MaxValue || TcpPortMapped.ContainsKey(LocalPort) || UdpPortMapped.ContainsKey(LocalPort)) { this.tcpListener.Stop(); this.tcpListener = null; if (this.desiredPort != 0) { throw new ArgumentException("Port already assigned to another application in the network.", "Port"); } } else { try { this.udpClient = new UdpClient(this.tcpListener.LocalEndpoint.AddressFamily); this.udpClient.Client.Bind((IPEndPoint)this.tcpListener.LocalEndpoint); } catch (Exception) { this.tcpListener.Stop(); this.tcpListener = null; } } }while (this.tcpListener is null); this.localEndpoint = new IPEndPoint(this.localAddress, LocalPort); this.serviceWANIPConnectionV1.AddPortMapping(string.Empty, LocalPort, "TCP", LocalPort, LocalAddress.ToString(), true, this.applicationName, 0); this.tcpMappingAdded = true; this.serviceWANIPConnectionV1.AddPortMapping(string.Empty, LocalPort, "UDP", LocalPort, LocalAddress.ToString(), true, this.applicationName, 0); this.udpMappingAdded = true; this.externalEndpoint = new IPEndPoint(this.externalAddress, LocalPort); this.State = PeerToPeerNetworkState.Ready; this.tcpListener.BeginAcceptTcpClient(this.EndAcceptTcpClient, null); this.udpClient.BeginReceive(this.EndReceiveUdp, null); } catch (Exception ex) { this.exception = ex; this.State = PeerToPeerNetworkState.Error; } }
protected Host(string name, string ip, string extIp, int port = 0, bool clientMode = false) : base() { this.IsClientMode = clientMode; Global.NetManager.OnConnect += OnConnect; Global.NetManager.OnReceive += OnReceive; Global.NetManager.OnClose += OnClose; Global.NetManager.OnException += OnExcept; Global.NetManager.OnHeartBeat += OnHeartBeat; //如果是客户端,则用本地连接做为id //如果是服务端,则从名称计算一个id, 方便路由查找 if (!clientMode) { string _ip = ip; string _extIp = extIp; int _port = port; if (ip == "auto") { _ip = Basic.GetLocalIPv4(NetworkInterfaceType.Ethernet); } if (extIp == "auto") { _extIp = Basic.GetLocalIPv4(NetworkInterfaceType.Ethernet); } if (port == 0) { _port = Basic.GetAvailablePort(IPAddress.Parse(_ip)); } this.LocalAddress = new IPEndPoint(IPAddress.Parse(_ip), _port); this.ExternalAddress = new IPEndPoint(IPAddress.Parse(_extIp), port); string addr = LocalAddress.ToIPv4String(); if (name == null) { this.UniqueName = Basic.GenID64().ToString(); } else { this.UniqueName = name; } this.Id = Basic.GenID64FromName(this.UniqueName); this.RegisterGlobalManager(this); Global.NetManager.RegisterHost(this); } else { if (name == null) { this.UniqueName = Basic.GenID64().ToString(); } else { this.UniqueName = name; } this.Id = Basic.GenID64FromName(this.UniqueName); Global.NetManager.RegisterHost(this); } if (!this.IsClientMode) { Log.Info(string.Format("{0}(ID:{1}) is running at {2} as ServerMode", this.UniqueName, this.Id, LocalAddress.ToString())); } else { Log.Info(string.Format("{0}(ID:{1}) is running as ClientMode", this.UniqueName, this.Id)); } this.AddRepeatedTimer(3000, 10000, () => { Global.NetManager.PrintPeerInfo("All peers:"); foreach (var a in this.actorDic.Values) { Log.Info("===========Actor info", a.Id, a.UniqueName); } Log.Info("End of Print"); }); }
private static void NetworkUpdated(object Sender, EventArgs e) { IUPnPDevice[] Devices = ssdpClient.Devices; Dictionary <string, IUPnPService> Prev = new Dictionary <string, IUPnPService> (); lock (stillImageCameras) { foreach (KeyValuePair <string, IUPnPService> Pair in stillImageCameras) { Prev [Pair.Key] = Pair.Value; } foreach (IUPnPDevice Device in Devices) { foreach (IUPnPService Service in Device.Services) { if (Service.ServiceType == "urn:schemas-upnp-org:service:DigitalSecurityCameraStillImage:1") { Prev.Remove(Device.UDN); if (!stillImageCameras.ContainsKey(Device.UDN)) { stillImageCameras [Device.UDN] = Service; Log.Information("Still image camera found.", EventLevel.Minor, Device.FriendlyName); ParsedUri Location = Web.ParseUri(Device.Location); string DeviceAddress = Location.Host; System.Net.IPHostEntry DeviceEntry = System.Net.Dns.GetHostEntry(DeviceAddress); string HostName = System.Net.Dns.GetHostName(); System.Net.IPHostEntry LocalEntry = System.Net.Dns.GetHostEntry(HostName); string LocalIP = null; foreach (System.Net.IPAddress LocalAddress in LocalEntry.AddressList) { foreach (System.Net.IPAddress RemoteAddress in DeviceEntry.AddressList) { if (LocalAddress.AddressFamily == RemoteAddress.AddressFamily) { LocalIP = LocalAddress.ToString(); break; } } if (LocalIP != null) { break; } } if (LocalIP != null) { int TimeoutSeconds = 5 * 60; string Callback = "http://" + LocalIP + ":" + upnpServer.Port.ToString() + "/events/" + Device.UDN; string Sid = Service.SubscribeToEvents(Callback, ref TimeoutSeconds); AddSubscription(TimeoutSeconds, new Subscription(Device.UDN, Sid, Service, LocalIP)); } } } } } foreach (KeyValuePair <string, IUPnPService> Pair in Prev) { Log.Information("Still image camera removed.", EventLevel.Minor, Pair.Value.Device.FriendlyName); stillImageCameras.Remove(Pair.Value.Device.UDN); foreach (KeyValuePair <DateTime, Subscription> Subscription in subscriptions) { if (Subscription.Value.UDN == Pair.Key) { subscriptions.Remove(Subscription.Key); break; } } } } lock (stateVariables) { foreach (KeyValuePair <string, IUPnPService> Pair in Prev) { stateVariables.Remove(Pair.Value.Device.UDN); } } }