Setting socket IP protection level causes an error only in Unity

Viewed 47

I am working on a multiplayer game in unity, and I'm currently trying to add automatic portforwarding.

In the code, a socket is made and listens on the port that was forwarded. For it to work, I set the IP protection level to unrestricted, so that anything over the internet can access it.

When I set it's protection level, I get this error: "System.Net.Sockets.SocketException (0x80004005): An unknown, invalid, or unsupported option or level was specified in a getsockopt or setsockopt call. "

I am using Unity 2021.3.9f1, and Open.NAT for the portforwarding. Here is the code:

using UnityEngine;
using Open.Nat;
using System.Net.Sockets;
using System;

public class AutomaticPortMapping : MonoBehaviour
{

    public async void Start()
    {

        NatDiscoverer discoverer = new NatDiscoverer();

        // using SSDP protocol, it discovers NAT device.
        NatDevice device = await discoverer.DiscoverDeviceAsync();

        // display the NAT's IP address
        IPAddress ip = await device.GetExternalIPAsync();
        print("The external IP Address is: " + ip);

        // create a new mapping in the router [external_ip:1702 -> host_machine:1602]
        await device.CreatePortMapAsync(new Mapping(Protocol.Udp, 1602, 1702, "For testing"));

        var endPoint = new IPEndPoint(IPAddress.Any, 1602);
        var socket = new Socket(endPoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
        try {
            socket.SetIPProtectionLevel(IPProtectionLevel.Unrestricted);
        } catch (Exception e) {
            print(e);
        }
        socket.Bind(endPoint);
        socket.Listen(4);
    }
}

I have tried changing Tcp to Udp, but that requires me to change the SocketType to raw, which requires a lot of extra permissions, and makes it very inconvenient.

0 Answers
Related