Hold up packages from network adepter and analyze it. Part 1
在這篇文章之中
我們直接調用socket來取得經由網路卡出入的封包
並且對封包的內容進行分析
我們先來看看取得封包的方式
首先建立一個socket
並且用 IOControl 這個成員函式來進行低階的控制設定
另外為了方便以後應用在多執行緒的程式上
我們採用非同步的方式來接收訊息
詳細的內容可以參考以下連結
http://msdn.microsoft.com/zh-tw/library/system.net.sockets.socket(v=VS.80).aspx
namespace WindowsFormsApplication1 { public class SocketMonitor { private Queue<AnalyzePackage> _qPackage; private Socket _mSocket; private AnalyzePackage _mPackage; private AnalyzePackage _mGetPackage; private readonly IPAddress _IP; private const int IOC_VENDOR = 0x18000000; private const int IOC_IN = -2147483648; private const int SIO_RCVALL = IOC_IN | IOC_VENDOR | 1; private byte[] _byBuff; public SocketMonitor(string IP) : this(IPAddress.Parse(IP)) { } /// <summary> /// Listening your network divice /// </summary> /// <param name="IP"></param> public SocketMonitor(IPAddress IP) { _IP = IP; _qPackage = new Queue<AnalyzePackage>(500); _byBuff = new byte[1024]; _mSocket = new Socket(AddressFamily.InterNetwork, SocketType.Raw, ProtocolType.IP); _mSocket.Bind(new IPEndPoint(_IP, 0)); // 0 will be listening all of ports. _mSocket.IOControl(SIO_RCVALL, BitConverter.GetBytes((int)1), null); this.BeginReceive(); } /// <summary> /// recurrent /// </summary> private void BeginReceive() { _mSocket.BeginReceive(_byBuff, 0, _byBuff.Length, SocketFlags.None, new AsyncCallback(OnReceive), null); } /// <summary> /// It will be called when you recive data /// </summary> /// <param name="SyncData"></param> private void OnReceive(IAsyncResult SyncData) { // get data length int iRecvLen_ = _mSocket.EndReceive(SyncData); _mPackage = new AnalyzePackage(_byBuff, iRecvLen_); lock (_qPackage) { _qPackage.Enqueue(_mPackage); } this.BeginReceive(); } /// <summary> /// Get package content from the queue. /// </summary> /// <returns></returns> public AnalyzePackage GetPackage() { _mGetPackage = null; lock (_qPackage) { if (_qPackage.Count!=0) _mGetPackage = _qPackage.Dequeue(); } return _mGetPackage; } /// <summary> /// Get count of the queue. /// </summary> public int PackageCount { get { return _qPackage.Count; } } } }
當每次取得資料時
OnReceive就會被呼叫
然後取得資料內容
接下來要做的
就是針對資料內容進行分析了
接續下篇…