Barotrauma Client Doc
LidgrenAddress.cs
1 #nullable enable
2 using System;
3 using System.Linq;
4 using System.Net;
5 using System.Net.Sockets;
6 
7 namespace Barotrauma.Networking
8 {
9  sealed class LidgrenAddress : Address
10  {
11  public readonly IPAddress NetAddress;
12 
13  public override string StringRepresentation
14  => NetAddress.ToString();
15 
16  public override bool IsLocalHost => IPAddress.IsLoopback(NetAddress);
17 
18  public LidgrenAddress(IPAddress netAddress)
19  {
20  if (IPAddress.IsLoopback(netAddress)) { netAddress = IPAddress.Loopback; }
21  if (netAddress.IsIPv4MappedToIPv6) { netAddress = netAddress.MapToIPv4(); }
22  NetAddress = netAddress;
23  }
24 
25  public new static Option<LidgrenAddress> Parse(string endpointStr)
26  {
27  if (endpointStr.Equals("localhost", StringComparison.OrdinalIgnoreCase))
28  {
29  return Option<LidgrenAddress>.Some(new LidgrenAddress(IPAddress.Loopback));
30  }
31  else if (IPAddress.TryParse(endpointStr, out IPAddress? netEndpoint))
32  {
33  return Option<LidgrenAddress>.Some(new LidgrenAddress(netEndpoint!));
34  }
35  return Option<LidgrenAddress>.None();
36  }
37 
38  public static Option<LidgrenAddress> ParseHostName(string endpointStr)
39  {
40  try
41  {
42  var resolvedAddresses = Dns.GetHostAddresses(endpointStr);
43  return resolvedAddresses.Any()
44  ? Option<LidgrenAddress>.Some(new LidgrenAddress(resolvedAddresses.First()))
46  }
47  catch (SocketException)
48  {
50  }
51  catch (ArgumentOutOfRangeException)
52  {
54  }
55  }
56 
57  public override bool Equals(object? obj)
58  => obj switch
59  {
60  LidgrenAddress otherAddress => this == otherAddress,
61  _ => false
62  };
63 
64  public override int GetHashCode()
65  => NetAddress.GetHashCode();
66 
67  public static bool operator ==(LidgrenAddress a, LidgrenAddress b)
68  {
69  var addressA = a.NetAddress.MapToIPv6();
70  var addressB = b.NetAddress.MapToIPv6();
71 
72  if (IPAddress.IsLoopback(addressA) && IPAddress.IsLoopback(addressB)) { return true; }
73  return addressA.Equals(addressB);
74  }
75 
76  public static bool operator !=(LidgrenAddress a, LidgrenAddress b)
77  => !(a == b);
78  }
79 }
LidgrenAddress(IPAddress netAddress)
override bool Equals(object? obj)
static Option< LidgrenAddress > ParseHostName(string endpointStr)
static new Option< LidgrenAddress > Parse(string endpointStr)
static bool operator!=(LidgrenAddress a, LidgrenAddress b)
static bool operator==(LidgrenAddress a, LidgrenAddress b)
static Option< T > Some(T value)
static UnspecifiedNone None
Definition: Option.cs:119