I am starting C# program for file sharing over local network, and it should be cappable of listing all users on local network that are using same program.
I am using UDP Broadcasting to announce existence of user in network, and there seems to be problem. When I run listener and then broadcast from the same computer, I do get response. But when I try to send broadcast from other device on same subnet I get nothing.
This is my broadcast-sending class:
public class BroadcastHelper
{
private int portNo;
private Socket brSock;
private IPEndPoint brEp;
public BroadcastHelper(int _portNo = 8888)
{
this.portNo = _portNo;
this.brSock = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
this.brSock.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Broadcast, 1);
this.brEp = new IPEndPoint(IPAddress.Broadcast, portNo);
}
public void SendBroadcast(string message)
{
byte[] buf = Encoding.ASCII.GetBytes(message);
brSock.SendTo(buf, this.brEp);
}
}
And this is my Listener code:
byte[] buf = new byte[1024];
var socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
var iep = new IPEndPoint(IPAddress.Any, 8888);
socket.Bind(iep);
var ep = iep as EndPoint;
socket.ReceiveFrom(buf, ref ep);
string msg = Encoding.ASCII.GetString(buf);
Console.WriteLine("Incoming message: " + msg);
Can someone tell me where is the problem, whether I must set some additional SocketOptions or I should use absolutely different technique to achieve this discovery ?
C# .NET 4.0