using System; using System.Net; using System.Text.RegularExpressions; using JD.Interfaces.Remoting; namespace JD.Remoting { /// /// The full identifier of a remote host to connect to (IP + Port). /// public struct EndPointId : IEndPointId { /// /// Use this Ip to listen to any ip. /// public const string AnyIp = "any"; /// /// Wheter the current instance was initialized using the explicit constructor. /// private readonly bool _initialized; private readonly string _ip; private readonly int _port; public EndPointId(string ip, int port) { Regex ipAddressRegex = new Regex(@"^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$"); if (ipAddressRegex.Match(ip).Success) { _ip = ip; } else { throw new Exception($"The Ip Address : {ip}, is NOT valid"); } _port = port; _initialized = true; } public static IEndPointId Default { get { return new EndPointId("127.0.0.1", 1001); } } public int Port { get { return _initialized ? _port : Default.Port; } } public string IP { get { return _initialized ? _ip : Default.IP; } } public IPAddress IpAddress { get { if (IP == AnyIp) { return IPAddress.Any; } else if (IP == Default.IP) { return IPAddress.Loopback; } return IPAddress.Parse(IP); } } public IEndPointId GetNextPort() { return new EndPointId(_ip, _port + 1); } /// public override string ToString() { return $"{IP}:{Port}"; } } }