How to open a UDP port from Unity without changing router settings?

I’m creating a program that is meant to listen for UDP packets from an external server, and when I manually open my ports through my router it works just fine, but I’d like to give this program to several friends who are unable to change router settings. I wanted to know if it would be possible to open the port through the application itself?

Starting function (runs once)

void StartGet(string textIn) {

// code to send message to server
// Message is a join request
// " Con [User] "

string[ ] splitText = textIn.Split(" ");

TargetName = splitText[1];

try {

/// Send join request to server.
remoteEndPoint = new IPEndPoint(IPAddress.Parse(ServerIP), ServerPortA);
client = new UdpClient();

byte[ ] data = Encoding.UTF8.GetBytes("Con " + TargetName); //Set connect code
client.Send(data, data.Length, remoteEndPoint); //Send connect code

client.Close(); // Close join request client

client = new UdpClient(ServerPortB); // Client for listening to server

/// Setup Osc server for forwarding
_oscOut = gameObject.AddComponent<OscOut>();
_oscOut.Open( 9000 , "127.0.0.1" );

/// Thread for listening to server.

receiveThread = new Thread(
new ThreadStart(GetThread));
receiveThread.IsBackground = true;
receiveThread.Start();

} catch (Exception err) {
Log("<color=\"red\"Error sending UDP packet</color>");
}
}

Background listener thread

private void GetThread() {
while (true) {

/// Listening to server
IPEndPoint anyIP = new IPEndPoint(IPAddress.Any, 0);
byte[ ] data = client.Receive(ref anyIP);

string incoming = Encoding.UTF8.GetString(data);
string[ ] SplitMessage = incoming.Split(" ");

print(incoming);

}
}

Tough question, definitely not Unity related.

But anyway, if at all, it’s got to be through a router feature called UPnP which allows programs to request the opening of a port respectively port forwarding. However, that feature may not be available on every router or it may be disabled for good reasons and lastly, even if its enabled on the router the local software firewall may block outgoing UPnP requests.

I have no idea how to interface with that service, I’m guessing it involves sending a broadcast packet. I mention it only for further research.

nat punch-through is usually mentioned in these cases… no idea if its solution here(?)

i’ve had this bookmarked, could have a look if it has solutions GitHub - 7wingfly/P2Pchat: A Peer-to-Peer chat program that demonstrates the implementation of UDP Hole-Punching, using a server with a known End Point to negotiate a direct connection between two clients behind NAT firewalls. Written in c#.

1 Like