Skip to content

Instantly share code, notes, and snippets.

@fversnel
Last active December 4, 2015 16:17
Show Gist options
  • Save fversnel/7143286f86b671ea019a to your computer and use it in GitHub Desktop.
Save fversnel/7143286f86b671ea019a to your computer and use it in GitHub Desktop.
Get available port for UNET socket
using System.Net;
using System.Net.Sockets;
using UnityEngine.Networking;

var address = IPAddress.Parse("0.0.0.0");
int port;
using (var tempSocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp)) {
    tempSocket.Bind(new IPEndPoint(address, port: 0));
    port = ((IPEndPoint) tempSocket.LocalEndPoint).Port;
}

var topology = new HostTopology(new ConnectionConfig(), maxDefaultConnections: 100);
var hostId = NetworkTransport.AddHost(topology, port, address.ToString());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment