Created
November 22, 2016 10:29
-
-
Save tmds/0684ad0f3e858879bd59913095240f15 to your computer and use it in GitHub Desktop.
MulticastInterface_Set_AnyInterface_Succeeds always hangs on Fedora 23/24
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.Net; | |
using System.Net.Sockets; | |
using System.Text; | |
using System.Threading.Tasks; | |
namespace ConsoleApplication | |
{ | |
public class Program | |
{ | |
public static void Main(string[] args) | |
{ | |
Console.WriteLine("Hello World!"); | |
MainAsync().Wait(); | |
} | |
public static async Task MainAsync() | |
{ | |
int interfaceIndex = 0; | |
IPAddress multicastAddress = IPAddress.Parse("239.1.2.3"); | |
string message = "hello"; | |
int port; | |
using (Socket receiveSocket = CreateBoundUdpSocket(out port), | |
sendSocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp)) | |
{ | |
receiveSocket.ReceiveTimeout = 1000; | |
receiveSocket.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.AddMembership, new MulticastOption(multicastAddress, interfaceIndex)); | |
sendSocket.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.MulticastInterface, IPAddress.HostToNetworkOrder(interfaceIndex)); | |
var receiveBuffer = new byte[1024]; | |
var receiveTask = receiveSocket.ReceiveAsync(new ArraySegment<byte>(receiveBuffer), SocketFlags.None); | |
for (int i = 0; i < 10; i++) | |
{ | |
System.Console.WriteLine("Send msg"); | |
sendSocket.SendTo(Encoding.UTF8.GetBytes(message), new IPEndPoint(multicastAddress, port)); | |
System.Console.WriteLine("Sent msg"); | |
} | |
System.Console.WriteLine("Await receive"); | |
int bytesReceived = await receiveTask; | |
System.Console.WriteLine("Finished await receive"); | |
string receivedMessage = Encoding.UTF8.GetString(receiveBuffer, 0, bytesReceived); | |
} | |
} | |
// Create an Udp Socket and binds it to an available port | |
private static Socket CreateBoundUdpSocket(out int localPort) | |
{ | |
Socket receiveSocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); | |
// sending a message will bind the socket to an available port | |
string sendMessage = "dummy message"; | |
int port = 54320; | |
IPAddress multicastAddress = IPAddress.Parse("239.1.1.1"); | |
receiveSocket.SendTo(Encoding.UTF8.GetBytes(sendMessage), new IPEndPoint(multicastAddress, port)); | |
localPort = (receiveSocket.LocalEndPoint as IPEndPoint).Port; | |
return receiveSocket; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment