Can I use TcpListener.AllowNatTraversal or Socket.SetIPProtectionLevel in Unity ?

Hello,

I’m implementing NAT Punchtrough with the library Open.NAT.
Everything works well except that the server needs to use a socket that allows Nat Traversal.

Unfortunately, the method .AllowNatTraversal(true) from a TcpListener, and the lower-level version, the method SetIPProtectionLevel(IPProtectionLevel.Unrestricted) from a Socket, both throw an error :

System.Net.Sockets.SocketException (0x80004005): An unknown, invalid, or unsupported option or level was specified in a getsockopt or setsockopt call.

Just in case, here is the socket version code :

var endPoint = new IPEndPoint(IPAddress.Any, 1602);
var socket = new Socket(endPoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
socket.SetIPProtectionLevel(IPProtectionLevel.Unrestricted);
socket.Bind(endPoint);
socket.Listen(4);

The exact same code works fine in a C# console program.

This error is only thrown in Unity.

Would anyone happen to have an idea why ?

Thank you for your time,

Galaad

First I would check all the arguments to ensure they are not null and then I would check the value of endPoint and socket before I use them. Additionally anytime you are performing these operations it good practice to have them in an if/then statement to handle errors so the program doesn’t crash if they are null or invalid but is instead handled by your own programming.

I suspect your socket.SetIPProtectionLevel is failing because the socket is null or -1 due to a bad socket call not a bad SetIPProtectionLevel call.