/// <summary> /// Starts the web server /// </summary> public static void StartWebServer() { if (WebsiteSettings.SettingsStore.EnableWebsite) { try { if (!LunaNetUtils.IsTcpPortInUse(WebsiteSettings.SettingsStore.Port)) { Server.Use(new TcpListenerAdapter(new TcpListener(IPAddress.Any, WebsiteSettings.SettingsStore.Port))); Server.Use(new ExceptionHandler()); Server.Use(new CompressionHandler(DeflateCompressor.Default, GZipCompressor.Default)); Server.Use(new FileHandler()); Server.Use(new HttpRouter().With(string.Empty, new RestHandler <ServerInformation>(new ServerInformationRestController(), JsonResponseProvider.Default))); Server.Start(); } else { LunaLog.Error("Could not start web server. Port is already in use."); LunaLog.Info("You can change the web server settings inside 'Config/WebsiteSettings.xml'"); } } catch (Exception e) { LunaLog.Error($"Could not start web server. Details: {e}"); } } }
public static void IntroduceToServer(long currentEntryId) { var token = RandomString(10); var ownEndpoint = new IPEndPoint(LunaNetUtils.GetMyAddress(), NetworkMain.Config.Port); LunaLog.Log($"[LMP]: Sending NAT introduction to server. Token: {token}"); var msgData = NetworkMain.CliMsgFactory.CreateNewMessageData <MsIntroductionMsgData>(); msgData.Id = currentEntryId; msgData.Token = token; msgData.InternalEndpoint = Common.StringFromEndpoint(ownEndpoint); var introduceMsg = MstSrvMsgFactory.CreateNew <MainMstSrvMsg>(msgData); foreach (var masterServer in MasterServerEndpoints.Values.ToArray()) { try { var lidgrenMsg = masterServer.CreateMessage((int)introduceMsg.GetMessageSize()); introduceMsg.Serialize(lidgrenMsg); masterServer.SendMessage(lidgrenMsg, introduceMsg.NetDeliveryMethod); masterServer.FlushSendQueue(); } catch (Exception e) { LunaLog.LogError($"[LMP]: Error connecting to server: {e}"); } } introduceMsg.Recycle(); }
/// <summary> /// Send a request to the master server to introduce us and do the nat punchtrough to the selected server /// </summary> public static void IntroduceToServer(long serverId) { if (Servers.TryGetValue(serverId, out var serverInfo)) { if (ServerIsInLocalLan(serverInfo.ExternalEndpoint)) { LunaLog.Log("Server is in LAN. Skipping NAT punch"); NetworkConnection.ConnectToServer(serverInfo.InternalEndpoint, Password); } else { try { var msgData = NetworkMain.CliMsgFactory.CreateNewMessageData <MsIntroductionMsgData>(); msgData.Id = serverId; msgData.Token = MainSystem.UniqueIdentifier; msgData.InternalEndpoint = new IPEndPoint(LunaNetUtils.GetOwnInternalIpAddress(), NetworkMain.Config.Port); var introduceMsg = NetworkMain.MstSrvMsgFactory.CreateNew <MainMstSrvMsg>(msgData); MainSystem.Singleton.Status = string.Empty; LunaLog.Log($"[LMP]: Sending NAT introduction to server. Token: {MainSystem.UniqueIdentifier}"); NetworkSender.QueueOutgoingMessage(introduceMsg); } catch (Exception e) { LunaLog.LogError($"[LMP]: Error connecting to server: {e}"); } } } }
public static async void RegisterWithMasterServer() { if (!GeneralSettings.SettingsStore.RegisterWithMasterServer) { return; } LunaLog.Normal("Registering with master servers..."); var adr = LunaNetUtils.GetMyAddress(); if (adr == null) { return; } var endpoint = new IPEndPoint(adr, ServerContext.Config.Port); while (ServerContext.ServerRunning) { var msgData = ServerContext.ServerMessageFactory.CreateNewMessageData <MsRegisterServerMsgData>(); msgData.Id = LidgrenServer.Server.UniqueIdentifier; msgData.Password = !string.IsNullOrEmpty(GeneralSettings.SettingsStore.Password); msgData.Cheats = GeneralSettings.SettingsStore.Cheats; msgData.ShowVesselsInThePast = GeneralSettings.SettingsStore.ShowVesselsInThePast; msgData.Description = GeneralSettings.SettingsStore.Description; msgData.DropControlOnExit = GeneralSettings.SettingsStore.Cheats; msgData.DropControlOnExitFlight = GeneralSettings.SettingsStore.Cheats; msgData.DropControlOnVesselSwitching = GeneralSettings.SettingsStore.Cheats; msgData.GameMode = (int)GeneralSettings.SettingsStore.GameMode; msgData.InternalEndpoint = $"{endpoint.Address}:{endpoint.Port}"; msgData.MaxPlayers = GeneralSettings.SettingsStore.MaxPlayers; msgData.ModControl = (int)GeneralSettings.SettingsStore.ModControl; msgData.PlayerCount = ServerContext.Clients.Count; msgData.ServerName = GeneralSettings.SettingsStore.ServerName; msgData.ServerVersion = LmpVersioning.CurrentVersion; msgData.VesselUpdatesSendMsInterval = GeneralSettings.SettingsStore.VesselUpdatesSendMsInterval; msgData.SecondaryVesselUpdatesSendMsInterval = GeneralSettings.SettingsStore.SecondaryVesselUpdatesSendMsInterval; msgData.WarpMode = (int)GeneralSettings.SettingsStore.WarpMode; msgData.TerrainQuality = (int)GeneralSettings.SettingsStore.TerrainQuality; msgData.Description = msgData.Description.Length > 200 ? msgData.Description.Substring(0, 200) : msgData.Description; msgData.ServerName = msgData.ServerName.Length > 30 ? msgData.ServerName.Substring(0, 30) : msgData.ServerName; lock (MasterServerEndpoints) { foreach (var masterServer in MasterServerEndpoints) { RegisterWithMasterServer(msgData, masterServer); } } await Task.Delay(MasterServerRegistrationMsInterval); } }
public static void ConnectToServer(string hostname, int port, string password) { ConnectToServer( LunaNetUtils.CreateAddressFromString(hostname).Select(ep => new IPEndPoint(ep, port)).ToArray(), password ); }
/// <summary> /// Send a request to the master server to introduce us and do the nat punchtrough to the selected server /// </summary> public static void IntroduceToServer(long serverId) { if (Servers.TryGetValue(serverId, out var serverInfo)) { var serverEndpoint = Common.CreateEndpointFromString(serverInfo.ExternalEndpoint); if (ServerIsInLocalLan(serverEndpoint)) { LunaLog.Log("Server is in LAN. Skipping NAT punch"); NetworkConnection.ConnectToServer(serverEndpoint.Address.ToString(), serverEndpoint.Port, Password); } else { try { var token = RandomString(10); var ownEndpoint = new IPEndPoint(LunaNetUtils.GetMyAddress(), NetworkMain.Config.Port); var msgData = NetworkMain.CliMsgFactory.CreateNewMessageData <MsIntroductionMsgData>(); msgData.Id = serverId; msgData.Token = token; msgData.InternalEndpoint = Common.StringFromEndpoint(ownEndpoint); var introduceMsg = NetworkMain.MstSrvMsgFactory.CreateNew <MainMstSrvMsg>(msgData); LunaLog.Log($"[LMP]: Sending NAT introduction to server. Token: {token}"); NetworkSender.QueueOutgoingMessage(introduceMsg); } catch (Exception e) { LunaLog.LogError($"[LMP]: Error connecting to server: {e}"); } } } }
/// <summary> /// Returns true if the server is running in a local LAN /// </summary> private static bool ServerIsInLocalLan(IPEndPoint serverEndPoint) { var ownNetwork = LunaNetUtils.GetOwnInternalIPv6Network(); if (ownNetwork != null && serverEndPoint.AddressFamily == AddressFamily.InterNetworkV6) { // For IPv6, we strip both addresses down to the subnet portion (likely the first 64 bits) and compare them. // Because we only receive Global Unique Addresses from GetOwnInternalIPv6Network() (which are globally // unique, as the name suggests and the RFCs define), those being equal should mean both are on the same network. var ownBytes = ownNetwork.Address.GetAddressBytes(); var serverBytes = serverEndPoint.Address.GetAddressBytes(); // TODO IPv6: We currently assume an on-link prefix length of 64 bits, which is the most common case // and standardized as per the RFCs. UnicastIPAddressInformation.PrefixLength is not implemented yet, // and also wouldn't be reliable (hosts often assign their address as /128). A possible solution could be // checking whether serverEndPoint matches any configured on-link/no-gateway route. Array.Resize(ref ownBytes, 8); Array.Resize(ref serverBytes, 8); if (ownBytes == serverBytes) { return(true); } } return(Equals(LunaNetUtils.GetOwnExternalIpAddress(), serverEndPoint.Address)); }
public Server(MsRegisterServerMsgData msg, IPEndPoint externalEndpoint) { Id = msg.Id; ExternalEndpoint = IsLocalIpAddress(externalEndpoint.Address) ? new IPEndPoint(LunaNetUtils.GetOwnExternalIpAddress(), externalEndpoint.Port) : externalEndpoint; Update(msg); }
public static void SetupLidgrenServer() { if (!IPAddress.TryParse(ConnectionSettings.SettingsStore.ListenAddress, out var listenAddress)) { LunaLog.Warning("Could not parse ListenAddress, falling back to 0.0.0.0"); listenAddress = IPAddress.Any; } ; ServerContext.Config.LocalAddress = listenAddress; // Listen on dual-stack for the unspecified address in IPv6 format ([::]). if (ServerContext.Config.LocalAddress.Equals(IPAddress.IPv6Any)) { ServerContext.Config.DualStack = true; } ServerContext.Config.Port = ConnectionSettings.SettingsStore.Port; ServerContext.Config.AutoExpandMTU = ConnectionSettings.SettingsStore.AutoExpandMtu; ServerContext.Config.MaximumTransmissionUnit = ConnectionSettings.SettingsStore.MaximumTransmissionUnit; ServerContext.Config.MaximumConnections = GeneralSettings.SettingsStore.MaxPlayers; ServerContext.Config.PingInterval = (float)TimeSpan.FromMilliseconds(ConnectionSettings.SettingsStore.HearbeatMsInterval).TotalSeconds; ServerContext.Config.ConnectionTimeout = (float)TimeSpan.FromMilliseconds(ConnectionSettings.SettingsStore.ConnectionMsTimeout).TotalSeconds; if (LunaNetUtils.IsUdpPortInUse(ServerContext.Config.Port)) { throw new HandledException($"Port {ServerContext.Config.Port} is already in use"); } ServerContext.Config.EnableMessageType(NetIncomingMessageType.ConnectionApproval); ServerContext.Config.EnableMessageType(NetIncomingMessageType.NatIntroductionSuccess); if (LogSettings.SettingsStore.LogLevel >= LogLevels.NetworkDebug) { ServerContext.Config.EnableMessageType(NetIncomingMessageType.DebugMessage); } if (LogSettings.SettingsStore.LogLevel >= LogLevels.VerboseNetworkDebug) { ServerContext.Config.EnableMessageType(NetIncomingMessageType.VerboseDebugMessage); } #if DEBUG if (DebugSettings.SettingsStore?.SimulatedLossChance < 100 && DebugSettings.SettingsStore?.SimulatedLossChance > 0) { ServerContext.Config.SimulatedLoss = DebugSettings.SettingsStore.SimulatedLossChance / 100f; } if (DebugSettings.SettingsStore?.SimulatedDuplicatesChance < 100 && DebugSettings.SettingsStore?.SimulatedLossChance > 0) { ServerContext.Config.SimulatedDuplicatesChance = DebugSettings.SettingsStore.SimulatedDuplicatesChance / 100f; } ServerContext.Config.SimulatedRandomLatency = (float)TimeSpan.FromMilliseconds((double)DebugSettings.SettingsStore?.MaxSimulatedRandomLatencyMs).TotalSeconds; ServerContext.Config.SimulatedMinimumLatency = (float)TimeSpan.FromMilliseconds((double)DebugSettings.SettingsStore?.MinSimulatedLatencyMs).TotalSeconds; #endif Server = new NetServer(ServerContext.Config); Server.Start(); ServerContext.ServerStarting = false; }
private static bool CheckPort() { if (LunaNetUtils.IsUdpPortInUse(Lidgren.MasterServer.Port)) { LunaLog.Fatal($"Port {Lidgren.MasterServer.Port} is already in use!"); return(false); } return(true); }
public static async void RegisterWithMasterServer() { if (!MasterServerSettings.SettingsStore.RegisterWithMasterServer) { return; } LunaLog.Normal("Registering with master servers..."); var adr = LunaNetUtils.GetOwnInternalIpAddress(); if (adr == null) { return; } var endpoint = new IPEndPoint(adr, ServerContext.Config.Port); while (ServerContext.ServerRunning) { var msgData = ServerContext.ServerMessageFactory.CreateNewMessageData <MsRegisterServerMsgData>(); msgData.Id = LidgrenServer.Server.UniqueIdentifier; msgData.Password = !string.IsNullOrEmpty(GeneralSettings.SettingsStore.Password); msgData.Cheats = GeneralSettings.SettingsStore.Cheats; msgData.Description = GeneralSettings.SettingsStore.Description; msgData.CountryCode = GeneralSettings.SettingsStore.CountryCode; msgData.Website = GeneralSettings.SettingsStore.Website; msgData.WebsiteText = GeneralSettings.SettingsStore.WebsiteText; msgData.RainbowEffect = DedicatedServerSettings.SettingsStore.UseRainbowEffect; msgData.Color = new[] { DedicatedServerSettings.SettingsStore.Red, DedicatedServerSettings.SettingsStore.Green, DedicatedServerSettings.SettingsStore.Blue }; msgData.GameMode = (int)GeneralSettings.SettingsStore.GameMode; msgData.InternalEndpoint = endpoint; msgData.MaxPlayers = GeneralSettings.SettingsStore.MaxPlayers; msgData.ModControl = GeneralSettings.SettingsStore.ModControl; msgData.PlayerCount = ServerContext.Clients.Count; msgData.ServerName = GeneralSettings.SettingsStore.ServerName; msgData.ServerVersion = LmpVersioning.CurrentVersion.ToString(3); msgData.VesselPositionUpdatesMsInterval = IntervalSettings.SettingsStore.VesselUpdatesMsInterval; msgData.SecondaryVesselPositionUpdatesMsInterval = IntervalSettings.SettingsStore.SecondaryVesselUpdatesMsInterval; msgData.WarpMode = (int)WarpSettings.SettingsStore.WarpMode; msgData.TerrainQuality = (int)GeneralSettings.SettingsStore.TerrainQuality; msgData.Description = msgData.Description.Length > 200 ? msgData.Description.Substring(0, 200) : msgData.Description; msgData.CountryCode = msgData.CountryCode.Length > 2 ? msgData.CountryCode.Substring(0, 2) : msgData.CountryCode; msgData.Website = msgData.Website.Length > 60 ? msgData.Website.Substring(0, 60) : msgData.Website; msgData.WebsiteText = msgData.WebsiteText.Length > 15 ? msgData.WebsiteText.Substring(0, 15) : msgData.WebsiteText; msgData.ServerName = msgData.ServerName.Length > 30 ? msgData.ServerName.Substring(0, 30) : msgData.ServerName; foreach (var masterServer in MasterServerRetriever.MasterServers.GetValues) { RegisterWithMasterServer(msgData, masterServer); } await Task.Delay(MasterServerRegistrationMsInterval); } }
/// <summary> /// Starts the web server /// </summary> public static void StartWebServer() { if (WebsiteSettings.SettingsStore.EnableWebsite) { try { if (!LunaNetUtils.IsTcpPortInUse(WebsiteSettings.SettingsStore.Port)) { IPAddress listenAddress; if (!string.IsNullOrEmpty(WebsiteSettings.SettingsStore.ListenAddress)) { // Custom ListenAddress for web server, parse it if (!IPAddress.TryParse(WebsiteSettings.SettingsStore.ListenAddress, out listenAddress)) { // Parsing failed, fall back to IPAddress.Any LunaLog.Warning( "Could not parse ListenAddress for web server, falling back to 0.0.0.0"); } } else { // ListenAddress unset for web server, try the one of the game server IPAddress.TryParse(ConnectionSettings.SettingsStore.ListenAddress, out listenAddress); } listenAddress ??= IPAddress.Any; var listener = new TcpListener(listenAddress, WebsiteSettings.SettingsStore.Port); // Listen on dual-stack for the unspecified address in IPv6 format ([::]). if (listenAddress.Equals(IPAddress.IPv6Any)) { listener.Server.DualMode = true; } Server.Use(new TcpListenerAdapter(listener)); Server.Use(new ExceptionHandler()); Server.Use(new CompressionHandler(DeflateCompressor.Default, GZipCompressor.Default)); Server.Use(new FileHandler()); Server.Use(new HttpRouter().With(string.Empty, new RestHandler <ServerInformation>(new ServerInformationRestController(), JsonResponseProvider.Default))); Server.Start(); } else { LunaLog.Error("Could not start web server. Port is already in use."); LunaLog.Info("You can change the web server settings inside 'Config/WebsiteSettings.xml'"); } } catch (Exception e) { LunaLog.Error($"Could not start web server. Details: {e}"); } } }
private static void CheckMasterServerListed() { var ownEndpoint = new IPEndPoint(LunaNetUtils.GetOwnExternalIpAddress(), Port); if (!MasterServerRetriever.MasterServers.Contains(ownEndpoint)) { LunaLog.Error($"You're not in the master-servers URL ({RepoConstants.MasterServersListShortUrl}) Clients/Servers won't see you"); } else { LunaLog.Normal("Own ip correctly listed in master - servers URL"); } }
private static void CheckMasterServerListed() { var servers = MasterServerRetriever.RetrieveWorkingMasterServersEndpoints(); var ownEndpoint = $"{LunaNetUtils.GetOwnExternalIpAddress()}:{Port}"; if (!servers.Contains(ownEndpoint)) { ConsoleLogger.Log(LogLevels.Error, $"You're not in the master-servers URL ({RepoConstants.MasterServersListShortUrl}) " + "Clients/Servers won't see you"); } else { ConsoleLogger.Log(LogLevels.Normal, "Own ip correctly listed in master - servers URL"); } }
public static void SetupLidgrenServer() { ServerContext.Config.Port = ConnectionSettings.SettingsStore.Port; ServerContext.Config.AutoExpandMTU = ConnectionSettings.SettingsStore.AutoExpandMtu; ServerContext.Config.MaximumTransmissionUnit = ConnectionSettings.SettingsStore.MaximumTransmissionUnit; ServerContext.Config.MaximumConnections = GeneralSettings.SettingsStore.MaxPlayers; ServerContext.Config.PingInterval = (float)TimeSpan.FromMilliseconds(ConnectionSettings.SettingsStore.HearbeatMsInterval).TotalSeconds; ServerContext.Config.ConnectionTimeout = (float)TimeSpan.FromMilliseconds(ConnectionSettings.SettingsStore.ConnectionMsTimeout).TotalSeconds; if (LunaNetUtils.IsUdpPortInUse(ServerContext.Config.Port)) { throw new HandledException($"Port {ServerContext.Config.Port} is already in use"); } ServerContext.Config.EnableMessageType(NetIncomingMessageType.ConnectionApproval); ServerContext.Config.EnableMessageType(NetIncomingMessageType.NatIntroductionSuccess); if (LogSettings.SettingsStore.LogLevel >= LogLevels.NetworkDebug) { ServerContext.Config.EnableMessageType(NetIncomingMessageType.DebugMessage); } if (LogSettings.SettingsStore.LogLevel >= LogLevels.VerboseNetworkDebug) { ServerContext.Config.EnableMessageType(NetIncomingMessageType.VerboseDebugMessage); } #if DEBUG if (DebugSettings.SettingsStore?.SimulatedLossChance < 100 && DebugSettings.SettingsStore?.SimulatedLossChance > 0) { ServerContext.Config.SimulatedLoss = DebugSettings.SettingsStore.SimulatedLossChance / 100f; } if (DebugSettings.SettingsStore?.SimulatedDuplicatesChance < 100 && DebugSettings.SettingsStore?.SimulatedLossChance > 0) { ServerContext.Config.SimulatedDuplicatesChance = DebugSettings.SettingsStore.SimulatedDuplicatesChance / 100f; } ServerContext.Config.SimulatedRandomLatency = (float)TimeSpan.FromMilliseconds((double)DebugSettings.SettingsStore?.MaxSimulatedRandomLatencyMs).TotalSeconds; ServerContext.Config.SimulatedMinimumLatency = (float)TimeSpan.FromMilliseconds((double)DebugSettings.SettingsStore?.MinSimulatedLatencyMs).TotalSeconds; #endif Server = new NetServer(ServerContext.Config); Server.Start(); ServerContext.ServerStarting = false; }
/// <summary> /// Download the dedicated server list from the <see cref="RepoConstants.DedicatedServersListUrl"/> and return the ones that are correctly written /// </summary> public static async Task RefreshDedicatedServersList() { while (MasterServer.RunServer) { try { ServicePointManager.ServerCertificateValidationCallback = GithubCertification.MyRemoteCertificateValidationCallback; using (var client = new WebClient()) using (var stream = client.OpenRead(RepoConstants.DedicatedServersListUrl)) { using (var reader = new StreamReader(stream)) { var content = await reader.ReadToEndAsync().ConfigureAwait(false); var servers = content .Trim() .Split('\n') .Where(s => !s.StartsWith("#") && s.Contains(":") && !string.IsNullOrEmpty(s)) .ToArray(); DedicatedServers.Clear(); foreach (var server in servers) { try { DedicatedServers.Add(LunaNetUtils.CreateEndpointFromString(server)); } catch (Exception) { //Ignore the bad server } } } } } catch (Exception) { //Ignored } await Task.Delay(RequestInterval).ConfigureAwait(false); } }
/// <summary> /// Gets my local IPv4 address (not necessarily external) and subnet mask /// </summary> public static IPAddress GetMyAddress(out IPAddress mask) { mask = null; #if UNITY_ANDROID || UNITY_STANDALONE_OSX || UNITY_STANDALONE_WIN || UNITY_STANDALONE_LINUX || UNITY_IOS || UNITY try { if (!(UnityEngine.Application.internetReachability == UnityEngine.NetworkReachability.NotReachable)) { return(null); } return(LunaNetUtils.GetOwnInternalIpAddress()); } catch // Catch Access Denied errors { return(null); } #endif return(null); }
private static void CheckMasterServerListed() { var ownAddress = LunaNetUtils.GetOwnExternalIpAddress(); if (ownAddress != null) { var ownEndpoint = new IPEndPoint(ownAddress, Port); if (!MasterServerRetriever.MasterServers.Contains(ownEndpoint)) { LunaLog.Error($"You're not listed in the master servers list ({RepoConstants.MasterServersListShortUrl}). Clients/Servers won't see you"); } else { LunaLog.Normal("You're correctly listed in the master servers list"); } } else { LunaLog.Error("Could not retrieve own external IP address, master server likely won't function properly"); } }
/// <summary> /// Send a request to the master server to introduce us and do the nat punchtrough to the selected server /// </summary> public static void IntroduceToServer(long currentEntryId) { try { var token = RandomString(10); var ownEndpoint = new IPEndPoint(LunaNetUtils.GetMyAddress(), NetworkMain.Config.Port); var msgData = NetworkMain.CliMsgFactory.CreateNewMessageData <MsIntroductionMsgData>(); msgData.Id = currentEntryId; msgData.Token = token; msgData.InternalEndpoint = Common.StringFromEndpoint(ownEndpoint); var introduceMsg = NetworkMain.MstSrvMsgFactory.CreateNew <MainMstSrvMsg>(msgData); LunaLog.Log($"[LMP]: Sending NAT introduction to server. Token: {token}"); NetworkSender.QueueOutgoingMessage(introduceMsg); } catch (Exception e) { LunaLog.LogError($"[LMP]: Error connecting to server: {e}"); } }
private static void RefreshMasterServersList() { try { ServicePointManager.ServerCertificateValidationCallback = GithubCertification.MyRemoteCertificateValidationCallback; using (var client = new WebClient()) using (var stream = client.OpenRead(RepoConstants.MasterServersListUrl)) { using (var reader = new StreamReader(stream)) { var content = reader.ReadToEnd(); var servers = content .Trim() .Split('\n') .Where(s => !s.StartsWith("#") && s.Contains(":") && !string.IsNullOrEmpty(s)) .ToArray(); MasterServersEndpoints.Clear(); foreach (var server in servers) { try { MasterServersEndpoints.Add(LunaNetUtils.CreateEndpointFromString(server)); } catch (Exception) { //Ignore the bad server } } } } } catch (Exception) { //Ignored } }
/// <summary> /// Returns true if the server is running in a local LAN /// </summary> private static bool ServerIsInLocalLan(IPEndPoint serverEndPoint) { return(LunaNetUtils.GetOwnExternalIpAddress() == serverEndPoint.Address.ToString()); }
/// <summary> /// Returns true if the server is running in a local LAN /// </summary> private static bool ServerIsInLocalLan(IPEndPoint serverEndPoint) { return(Equals(LunaNetUtils.GetOwnExternalIpAddress(), serverEndPoint.Address)); }
public Server(MsRegisterServerMsgData msg, IPEndPoint externalEndpoint) { ExternalEndpoint = IsLocalIpAddress(externalEndpoint.Address) ? new IPEndPoint(IPAddress.Parse(LunaNetUtils.GetOwnExternalIpAddress()), externalEndpoint.Port) : externalEndpoint; InternalEndpoint = Common.CreateEndpointFromString(msg.InternalEndpoint); LastRegisterTime = LunaTime.UtcNow.Ticks; Info = new ServerInfo { Id = msg.Id, ExternalEndpoint = $"{ExternalEndpoint.Address}:{ExternalEndpoint.Port}", InternalEndpoint = $"{InternalEndpoint.Address}:{InternalEndpoint.Port}", Cheats = msg.Cheats, Password = msg.Password, ServerVersion = msg.ServerVersion, ShowVesselsInThePast = msg.ShowVesselsInThePast, Description = msg.Description, DropControlOnExit = msg.DropControlOnExit, DropControlOnExitFlight = msg.DropControlOnExitFlight, DropControlOnVesselSwitching = msg.DropControlOnVesselSwitching, GameMode = msg.GameMode, MaxPlayers = msg.MaxPlayers, ModControl = msg.ModControl, PlayerCount = msg.PlayerCount, ServerName = msg.ServerName, WarpMode = msg.WarpMode, TerrainQuality = msg.TerrainQuality }; Info.ServerName = Info.ServerName.Length > 30 ? Info.ServerName.Substring(0, 30) : Info.ServerName; Info.Description = Info.Description.Length > 200 ? Info.Description.Substring(0, 200) : Info.Description; }
public static async void RegisterWithMasterServer() { if (!MasterServerSettings.SettingsStore.RegisterWithMasterServer) { return; } LunaLog.Normal("Registering with master servers"); var adr4 = LunaNetUtils.GetOwnInternalIPv4Address(); // As of right now the internal endpoint for IPv4 is mandatory, because if there is none, there is no // IPv4 connectivity at all, which is required to connect to the master servers (so they can determine // the public IPv4 address). if (adr4 == null) { return; } var endpoint4 = new IPEndPoint(adr4, ServerContext.Config.Port); // Only send IPv6 address if actually listening on IPv6, otherwise send loopback with means "none". IPAddress adr6; IPEndPoint endpoint6; if (LidgrenServer.Server.Socket.AddressFamily == AddressFamily.InterNetworkV6) { adr6 = LunaNetUtils.GetOwnInternalIPv6Address(); endpoint6 = new IPEndPoint(adr6, ServerContext.Config.Port); } else { endpoint6 = new IPEndPoint(IPAddress.IPv6Loopback, ServerContext.Config.Port); } while (ServerContext.ServerRunning) { var msgData = ServerContext.ServerMessageFactory.CreateNewMessageData <MsRegisterServerMsgData>(); msgData.Id = LidgrenServer.Server.UniqueIdentifier; msgData.Password = !string.IsNullOrEmpty(GeneralSettings.SettingsStore.Password); msgData.Cheats = GeneralSettings.SettingsStore.Cheats; msgData.Description = GeneralSettings.SettingsStore.Description; msgData.CountryCode = GeneralSettings.SettingsStore.CountryCode; msgData.Website = GeneralSettings.SettingsStore.Website; msgData.WebsiteText = GeneralSettings.SettingsStore.WebsiteText; msgData.RainbowEffect = DedicatedServerSettings.SettingsStore.UseRainbowEffect; msgData.Color = new[] { DedicatedServerSettings.SettingsStore.Red, DedicatedServerSettings.SettingsStore.Green, DedicatedServerSettings.SettingsStore.Blue }; msgData.GameMode = (int)GeneralSettings.SettingsStore.GameMode; msgData.InternalEndpoint = endpoint4; msgData.InternalEndpoint6 = endpoint6; msgData.MaxPlayers = GeneralSettings.SettingsStore.MaxPlayers; msgData.ModControl = GeneralSettings.SettingsStore.ModControl; msgData.PlayerCount = ServerContext.Clients.Count; msgData.ServerName = GeneralSettings.SettingsStore.ServerName; msgData.ServerVersion = LmpVersioning.CurrentVersion.ToString(3); msgData.VesselPositionUpdatesMsInterval = IntervalSettings.SettingsStore.VesselUpdatesMsInterval; msgData.SecondaryVesselPositionUpdatesMsInterval = IntervalSettings.SettingsStore.SecondaryVesselUpdatesMsInterval; msgData.WarpMode = (int)WarpSettings.SettingsStore.WarpMode; msgData.TerrainQuality = (int)GeneralSettings.SettingsStore.TerrainQuality; msgData.Description = msgData.Description.Length > 200 ? msgData.Description.Substring(0, 200) : msgData.Description; msgData.CountryCode = msgData.CountryCode.Length > 2 ? msgData.CountryCode.Substring(0, 2) : msgData.CountryCode; msgData.Website = msgData.Website.Length > 60 ? msgData.Website.Substring(0, 60) : msgData.Website; msgData.WebsiteText = msgData.WebsiteText.Length > 15 ? msgData.WebsiteText.Substring(0, 15) : msgData.WebsiteText; msgData.ServerName = msgData.ServerName.Length > 30 ? msgData.ServerName.Substring(0, 30) : msgData.ServerName; IPEndPoint[] masterServers; if (string.IsNullOrEmpty(DebugSettings.SettingsStore.CustomMasterServer)) { masterServers = MasterServerRetriever.MasterServers.GetValues; } else { masterServers = new[] { LunaNetUtils.CreateEndpointFromString(DebugSettings.SettingsStore.CustomMasterServer) }; } foreach (var masterServer in masterServers) { RegisterWithMasterServer(msgData, masterServer); } await Task.Delay(MasterServerRegistrationMsInterval); } }
/// <summary> /// Sends the network message. It will skip client messages to send when we are not connected, /// except if it's directed at master servers, then it will start the NetClient and socket. /// </summary> private static void SendNetworkMessage(IMessageBase message) { message.Data.SentTime = LunaNetworkTime.UtcNow.Ticks; try { if (message is IMasterServerMessageBase) { if (NetworkMain.ClientConnection.Status == NetPeerStatus.NotRunning) { LunaLog.Log("Starting client to send unconnected message"); NetworkMain.ClientConnection.Start(); } while (NetworkMain.ClientConnection.Status != NetPeerStatus.Running) { LunaLog.Log("Waiting for client to start up to send unconnected message"); // Still trying to start up Thread.Sleep(50); } IPEndPoint[] masterServers; if (string.IsNullOrEmpty(SettingsSystem.CurrentSettings.CustomMasterServer)) { masterServers = MasterServerRetriever.MasterServers.GetValues; } else { masterServers = new[] { LunaNetUtils.CreateEndpointFromString(SettingsSystem.CurrentSettings.CustomMasterServer) }; } foreach (var masterServer in masterServers) { // Don't reuse lidgren messages, it does that on it's own var lidgrenMsg = NetworkMain.ClientConnection.CreateMessage(message.GetMessageSize()); message.Serialize(lidgrenMsg); NetworkMain.ClientConnection.SendUnconnectedMessage(lidgrenMsg, masterServer); } // Force send of packets NetworkMain.ClientConnection.FlushSendQueue(); } else { if (NetworkMain.ClientConnection == null || NetworkMain.ClientConnection.Status == NetPeerStatus.NotRunning || MainSystem.NetworkState < ClientState.Connected) { return; } var lidgrenMsg = NetworkMain.ClientConnection.CreateMessage(message.GetMessageSize()); message.Serialize(lidgrenMsg); NetworkMain.ClientConnection.SendMessage(lidgrenMsg, message.NetDeliveryMethod, message.Channel); // Force send of packets NetworkMain.ClientConnection.FlushSendQueue(); } message.Recycle(); } catch (Exception e) { NetworkMain.HandleDisconnectException(e); } }
public Server(MsRegisterServerMsgData msg, IPEndPoint externalEndpoint) { ExternalEndpoint = IsLocalIpAddress(externalEndpoint.Address) ? new IPEndPoint(IPAddress.Parse(LunaNetUtils.GetOwnExternalIpAddress()), externalEndpoint.Port) : externalEndpoint; InternalEndpoint = Common.CreateEndpointFromString(msg.InternalEndpoint); LastRegisterTime = LunaNetworkTime.UtcNow.Ticks; Info = new ServerInfo { Id = msg.Id, ExternalEndpoint = $"{ExternalEndpoint.Address}:{ExternalEndpoint.Port}", InternalEndpoint = $"{InternalEndpoint.Address}:{InternalEndpoint.Port}", Cheats = msg.Cheats, Password = msg.Password, ServerVersion = msg.ServerVersion, Description = msg.Description, Website = msg.Website, WebsiteText = msg.WebsiteText, DropControlOnExit = msg.DropControlOnExit, DropControlOnExitFlight = msg.DropControlOnExitFlight, DropControlOnVesselSwitching = msg.DropControlOnVesselSwitching, GameMode = msg.GameMode, MaxPlayers = msg.MaxPlayers, ModControl = msg.ModControl, PlayerCount = msg.PlayerCount, ServerName = msg.ServerName, WarpMode = msg.WarpMode, TerrainQuality = msg.TerrainQuality, }; SetCountryFromEndpoint(Info, ExternalEndpoint); Info.ServerName = Info.ServerName.Length > 30 ? Info.ServerName.Substring(0, 30) : Info.ServerName; Info.Description = Info.Description.Length > 200 ? Info.Description.Substring(0, 200) : Info.Description; Info.Website = Info.Website.Length > 60 ? Info.Website.Substring(0, 60) : Info.Website; Info.WebsiteText = Info.WebsiteText.Length > 15 ? Info.WebsiteText.Substring(0, 15) : Info.WebsiteText; if (!string.IsNullOrEmpty(Info.Website) && !Info.Website.Contains("://")) { Info.Website = "http://" + Info.Website; } if (string.IsNullOrEmpty(Info.WebsiteText) && !string.IsNullOrEmpty(Info.Website)) { Info.WebsiteText = "URL"; } }
public static void ConnectToServer(string address, int port, string password) { ConnectToServer(new IPEndPoint(LunaNetUtils.CreateAddressFromString(address), port), password); }