private Socket _serverSocket;
private bool _active;
private bool _exclusiveAddressUse;
+ private bool? _allowNatTraversal;
// Initializes a new instance of the TcpListener class with the specified local end point.
public TcpListener(IPEndPoint localEP)
throw new InvalidOperationException(SR.net_tcplistener_mustbestopped);
}
- _serverSocket.SetIPProtectionLevel(allowed ? IPProtectionLevel.Unrestricted : IPProtectionLevel.EdgeRestricted);
+ if (_serverSocket != null)
+ {
+ SetIPProtectionLevel(allowed); // Set it only for the current socket to preserve existing behavior
+ }
+ else
+ {
+ _allowNatTraversal = allowed;
+ }
}
// Starts listening to network requests.
return listener;
}
+ private void SetIPProtectionLevel(bool allowed)
+ => _serverSocket.SetIPProtectionLevel(allowed ? IPProtectionLevel.Unrestricted : IPProtectionLevel.EdgeRestricted);
+
private void CreateNewSocketIfNeeded()
{
_serverSocket ??= new Socket(_serverSocketEP.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
{
_serverSocket.ExclusiveAddressUse = true;
}
+
+ if (_allowNatTraversal != null)
+ {
+ SetIPProtectionLevel(_allowNatTraversal.GetValueOrDefault());
+ _allowNatTraversal = null; // Reset value to avoid affecting more sockets
+ }
}
}
}
}
[Fact]
+ [PlatformSpecific(TestPlatforms.Windows)]
+ public void AllowNatTraversal_NotStarted_SetSuccessfully()
+ {
+ var listener = new TcpListener(IPAddress.Loopback, 0);
+ listener.AllowNatTraversal(true);
+ listener.Start();
+ listener.Stop();
+ }
+
+ [Fact]
+ [PlatformSpecific(TestPlatforms.Windows)]
+ public void AllowNatTraversal_Started_ThrowsException()
+ {
+ var listener = new TcpListener(IPAddress.Loopback, 0);
+ listener.Start();
+ Assert.Throws<InvalidOperationException>(() => listener.AllowNatTraversal(true));
+ listener.Stop();
+ }
+
+ [Fact]
+ [PlatformSpecific(TestPlatforms.Windows)]
+ public void AllowNatTraversal_StartedAndStopped_SetSuccessfully()
+ {
+ var listener = new TcpListener(IPAddress.Loopback, 0);
+ listener.Start();
+ listener.Stop();
+ listener.AllowNatTraversal(true);
+ }
+
+ [Fact]
public void Start_InvalidArgs_Throws()
{
var listener = new DerivedTcpListener(IPAddress.Loopback, 0);