2

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

Meyhem
  • 91
  • 1
  • 9
  • 1
    Did you try multicast instead? Seems to me broadcasts are not liked by network equipment that much. As for _discovery_ have a look at this question as well: http://stackoverflow.com/questions/23483495/how-do-you-discover-a-tcplistener-services-ipaddress – mtmk Jul 02 '14 at 17:32
  • In many cases broadcasts are explicitly blocked on networks. My Linksys router, for instance, blocked all UDP broadcasts by default when I bought it. – Leon Newswanger Jul 02 '14 at 18:00
  • @Maxwell Troy Milton King After bit reading about multicasting, seems like this is exactly what I was looking for. Thank you. – Meyhem Jul 02 '14 at 18:00

0 Answers0