How to listen for broadcast packets on any port?

北战南征 提交于 2019-12-07 05:28:44

问题


Using .NET, how can I listen to udp broadcast packets sent to .255 on any port without the need of binding to a specific port?


回答1:


I found a way myself. This is how it works:

mainSocket = new Socket(AddressFamily.InterNetwork, SocketType.Raw, ProtocolType.IP);
mainSocket.Bind(new IPEndPoint(IPAddress.Parse("192.168.0.1"), 0));
mainSocket.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.HeaderIncluded, true);                           

byte[] byTrue = new byte[4] { 1, 0, 0, 0 };
byte[] byOut = new byte[4] { 1, 0, 0, 0 }; 

// Socket.IOControl is analogous to the WSAIoctl method of Winsock 2
mainSocket.IOControl(IOControlCode.ReceiveAll, //Equivalent to SIO_RCVALL constant of Winsock 2
    byTrue,
    byOut);

//Start receiving the packets asynchronously
mainSocket.BeginReceive(byteData,0,byteData.Length,SocketFlags.None,new AsyncCallback(OnReceive),null);

In the async handler, I do a mainSocket.EndReceive(...), parse the data and start a new BeginReceive if wanted (controlled from outside the multithreaded receiver).

Works like a charm. Credits go to Hitesh Sharma (http://www.codeproject.com/KB/IP/CSNetworkSniffer.aspx)




回答2:


I think you'll need to be lower level than UDP to accomplish this.

If I really wanted to do this, I'd start by downloading an open source packet sniffer/network analyzer (Ethereal.com comes to mind) and peruse the source to see how they read the packets.

Looking further, I found quite a bit about packet capturing at tcpdump.org.

Sorry I can't give specific code snippets, I've always wanted to bind to a specific port.




回答3:


You'll need to use WinPCap or similar to sniff packets at the link level, then filter for UDP broadcasts. Sorry, I don't think there's any higher level API for this.



来源:https://stackoverflow.com/questions/1233041/how-to-listen-for-broadcast-packets-on-any-port

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!