Created
May 20, 2019 18:53
-
-
Save citizenmatt/b8fed74716a04a78f459895112ca31aa to your computer and use it in GitHub Desktop.
Unity UDP broadcast listener
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Collections.Generic; | |
using System.Net; | |
using System.Net.NetworkInformation; | |
using System.Net.Sockets; | |
using System.Text; | |
namespace UdpTest | |
{ | |
internal class Program | |
{ | |
public static readonly int[] PLAYER_MULTICAST_PORTS = new[]{ 54997, 34997, 57997, 58997 }; | |
public const string PLAYER_MULTICAST_GROUP = "225.0.0.222"; | |
public static void Main(string[] args) | |
{ | |
var sockets = new List<Socket>(); | |
var nics = NetworkInterface.GetAllNetworkInterfaces(); | |
foreach (var networkInterface in nics) | |
{ | |
if (!networkInterface.Supports(NetworkInterfaceComponent.IPv4)) | |
continue; | |
var interfaceProperties = networkInterface.GetIPProperties(); | |
var p = interfaceProperties.GetIPv4Properties(); | |
foreach (var port in PLAYER_MULTICAST_PORTS) | |
{ | |
try | |
{ | |
var socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); | |
socket.ExclusiveAddressUse = false; | |
socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true); | |
var ipEndPoint = new IPEndPoint(IPAddress.Any, port); | |
socket.Bind(ipEndPoint); | |
var ip = IPAddress.Parse(PLAYER_MULTICAST_GROUP); | |
socket.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.AddMembership, new MulticastOption(ip, p.Index)); | |
sockets.Add(socket); | |
} | |
catch (Exception e) | |
{ | |
Console.WriteLine(e); | |
throw; | |
} | |
} | |
} | |
Console.WriteLine("Set up {0} sockets across {1} interfaces", sockets.Count, nics.Length); | |
long messages = 0; | |
while (true) | |
{ | |
var buffer = new byte[1024]; | |
foreach (var socket in sockets) | |
{ | |
while (socket.Available > 0) | |
{ | |
var received = socket.Receive(buffer); | |
var str = Encoding.ASCII.GetString(buffer, 0, received); | |
Console.WriteLine("Received({1}): {0}", str, ++messages); | |
} | |
} | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment