如何监听任何端口上的广播包? [英] How to listen for broadcast packets on any port?

查看:330
本文介绍了如何监听任何端口上的广播包?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用.NET,我怎么能听不绑定到特定端口需要发送到.255任何端口的UDP广播包?

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?

推荐答案

我找到了一种方法自己。这是如何工作的:

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);

在异步处理程序中,我做了mainSocket.EndReceive(...),分析数据,并开始一个新的BeginReceive如果想(从多线程的接收器外控制)。

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).

工程就像一个魅力。积分去亚太区首席技术官Matt夏尔马(<一href="http://www.$c$cproject.com/KB/IP/CSNetworkSniffer.aspx">http://www.$c$cproject.com/KB/IP/CSNetworkSniffer.aspx)

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

这篇关于如何监听任何端口上的广播包?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆