using System; using System.Collections.Generic; using System.Net; using System.Net.NetworkInformation; using System.Net.Sockets; using System.Text; using UnityEngine; namespace GrassCutter { public struct LanGame { public string ip, name; public ushort port; public int members, max; public float seen; } /// /// Games on the local network find each other without Steam: a LAN host shouts its port once a second on UDP, and the game /// browser listens. Everything runs on the main thread from ; the sockets never block. /// public static class LanBeacon { public const int Port = 47797; const string Tag = "GCT1"; const float Every = 1f, Forget = 4f; static UdpClient _send, _listen; static string _name; static ushort _gamePort; static float _next; static readonly string Nonce = Guid.NewGuid().ToString("N").Substring(0, 8); static readonly Dictionary _found = new Dictionary(); static List _targets; public static bool Hosting => _send != null; // ───────────────────────── hosting ───────────────────────── public static void Host(string name, ushort gamePort) { Stop(); try { _send = new UdpClient(AddressFamily.InterNetwork) { EnableBroadcast = true }; _name = name.Replace("|", "/"); _gamePort = gamePort; _targets = Targets(); _next = 0f; Debug.Log($"[LAN] announcing on port {Port}, game on {gamePort}, {_targets.Count} target(s)"); } catch (Exception e) { Debug.LogWarning("[LAN] can't announce: " + e.Message); _send = null; } } public static void Stop() { _send?.Close(); _send = null; } /// The broadcast address of every network the PC is on, plus itself for a second copy on the same PC. static List Targets() { var list = new List { new IPEndPoint(IPAddress.Broadcast, Port), new IPEndPoint(IPAddress.Loopback, Port) }; try { foreach (var nic in NetworkInterface.GetAllNetworkInterfaces()) { if (nic.OperationalStatus != OperationalStatus.Up || nic.NetworkInterfaceType == NetworkInterfaceType.Loopback) continue; foreach (var a in nic.GetIPProperties().UnicastAddresses) { if (a.Address.AddressFamily != AddressFamily.InterNetwork || a.IPv4Mask == null) continue; var ip = a.Address.GetAddressBytes(); var mask = a.IPv4Mask.GetAddressBytes(); if (mask.Length != 4 || mask[0] == 0) continue; for (int i = 0; i < 4; i++) ip[i] = (byte)(ip[i] | ~mask[i]); var to = new IPEndPoint(new IPAddress(ip), Port); if (!list.Exists(t => t.Equals(to))) list.Add(to); } } } catch (Exception e) { Debug.LogWarning("[LAN] can't list networks: " + e.Message); } return list; } // ───────────────────────── looking ───────────────────────── public static void Listen() { if (_listen != null) return; _found.Clear(); try { _listen = new UdpClient(AddressFamily.InterNetwork); _listen.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true); _listen.Client.Bind(new IPEndPoint(IPAddress.Any, Port)); } catch (Exception e) { Debug.LogWarning("[LAN] can't listen: " + e.Message); _listen?.Close(); _listen = null; } } public static void StopListening() { _listen?.Close(); _listen = null; } /// Games heard in the last few seconds, other than our own. public static List Found() { var list = new List(); foreach (var g in _found.Values) if (Time.unscaledTime - g.seen < Forget) list.Add(g); list.Sort((a, b) => string.CompareOrdinal(a.name, b.name)); return list; } // ───────────────────────── pump ───────────────────────── public static void Tick(int members, int max) { if (_send != null && Time.unscaledTime >= _next) { _next = Time.unscaledTime + Every; var bytes = Encoding.UTF8.GetBytes($"{Tag}|{NetSession.Version}|{Nonce}|{_gamePort}|{members}|{max}|{_name}"); foreach (var to in _targets) try { _send.Send(bytes, bytes.Length, to); } catch (SocketException) { } // a network that went away: the others still hear } if (_listen == null) return; try { while (_listen.Available > 0) { var from = new IPEndPoint(IPAddress.Any, 0); var data = _listen.Receive(ref from); Heard(Encoding.UTF8.GetString(data), from.Address); } } catch (Exception e) { Debug.LogWarning("[LAN] listening stopped: " + e.Message); StopListening(); } } static void Heard(string msg, IPAddress from) { var p = msg.Split(new[] { '|' }, 7); if (p.Length < 7 || p[0] != Tag || p[1] != NetSession.Version) return; if (p[2] == Nonce) return; if (!ushort.TryParse(p[3], out ushort port) || !int.TryParse(p[4], out int members) || !int.TryParse(p[5], out int max)) return; string key = p[2]; // the same host is heard on the network and on loopback: keep the network address, so others can type it too string ip = from.ToString(); if (_found.TryGetValue(key, out var old) && IPAddress.IsLoopback(from) && !IPAddress.Parse(old.ip).Equals(IPAddress.Loopback)) ip = old.ip; _found[key] = new LanGame { ip = ip, port = port, members = members, max = max, name = p[6], seen = Time.unscaledTime }; } // ───────────────────────── ports ───────────────────────── /// The wanted port if nothing on this PC holds it, otherwise any free one. public static ushort FreePort(ushort want) { try { using (new UdpClient(want)) return want; } catch (SocketException) { } using (var any = new UdpClient(0)) return (ushort)((IPEndPoint)any.Client.LocalEndPoint).Port; } /// This PC's addresses on the local network, for players who type them in. public static string MyAddresses() { var list = new List(); try { foreach (var nic in NetworkInterface.GetAllNetworkInterfaces()) { if (nic.OperationalStatus != OperationalStatus.Up || nic.NetworkInterfaceType == NetworkInterfaceType.Loopback) continue; foreach (var a in nic.GetIPProperties().UnicastAddresses) if (a.Address.AddressFamily == AddressFamily.InterNetwork && !a.Address.ToString().StartsWith("169.254.")) list.Add(a.Address.ToString()); } } catch (Exception) { } return string.Join(", ", list); } } }