本文向大家介紹Windows Sockets的一些關于用C#實現(xiàn)的原始套接字(Raw Socket)的編程,以及在此基礎上實現(xiàn)的網(wǎng)絡封包監(jiān)視技術。同Winsock1相比,Winsock2最明顯的就是支持了Raw Socket套接字類型,使用Raw Socket,可把網(wǎng)卡設置成混雜模式,在這種模式下,我們可以收到網(wǎng)絡上的IP包,當然包括目的不是本機的IP包,通過原始套接字,我們也可以更加自如地控制Windows下的多種協(xié)議,而且能夠?qū)W(wǎng)絡底層的傳輸機制進行控制。
談起socket編程,大家也許會想起QQ和IE,沒錯。還有許多網(wǎng)絡工具如P2P、NetMeeting等在應用層實現(xiàn)的應用程序,也是用socket來實現(xiàn)的。Socket是一個網(wǎng)絡編程接口,實現(xiàn)于網(wǎng)絡應用層,Windows Socket包括了一套系統(tǒng)組件,充分利用了Microsoft Windows 消息驅(qū)動的特點。Socket規(guī)范1.1版是在1993年1月發(fā)行的,并廣泛用于此后出現(xiàn)的Windows9x操作系統(tǒng)中。Socket規(guī)范2.2版(其在Windows平臺上的版本是Winsock2.2,也叫Winsock2)在 1996 年 5 月發(fā)行,Windows NT 5.0及以后版本的Windows系統(tǒng)支持Winsock2,在Winsock2中,支持多個傳輸協(xié)議的原始套接字,重疊I/O模型、服務質(zhì)量控制等。
在本文例子中,我在nbyte.BasicClass命名空間實現(xiàn)了RawSocket類,它包含了我們實現(xiàn)數(shù)據(jù)包監(jiān)視的核心技術。在實現(xiàn)這個類之前,需要先寫一個IP頭結構,來暫時存放一些有關網(wǎng)絡封包的信息:
[StructLayout(LayoutKind.Explicit)] public struct IPHeader { [FieldOffset(0)] public byte ip_verlen; //I4位首部長度+4位IP版本號 [FieldOffset(1)] public byte ip_tos; //8位服務類型TOS [FieldOffset(2)] public ushort ip_totallength; //16位數(shù)據(jù)包總長度(字節(jié)) [FieldOffset(4)] public ushort ip_id; //16位標識 [FieldOffset(6)] public ushort ip_offset; //3位標志位 [FieldOffset(8)] public byte ip_ttl; //8位生存時間 TTL [FieldOffset(9)] public byte ip_protocol; //8位協(xié)議(TCP, UDP, ICMP, Etc.) [FieldOffset(10)] public ushort ip_checksum; //16位IP首部校驗和 [FieldOffset(12)] public uint ip_srcaddr; //32位源IP地址 [FieldOffset(16)] public uint ip_destaddr; //32位目的IP地址 } |
private bool error_occurred; //套接字在接收包時是否產(chǎn)生錯誤 public bool KeepRunning; //是否繼續(xù)進行 private static int len_receive_buf; //得到的數(shù)據(jù)流的長度 byte [] receive_buf_bytes; //收到的字節(jié) private Socket socket = null; //聲明套接字 |
const int SIO_RCVALL = unchecked((int)0x98000001);//監(jiān)聽所有的數(shù)據(jù)包 |
public RawSocket() //構造函數(shù) { error_occurred=false; len_receive_buf = 4096; receive_buf_bytes = new byte[len_receive_buf]; } |
public void CreateAndBindSocket(string IP) //建立并綁定套接字 { socket = new Socket(AddressFamily.InterNetwork, SocketType.Raw, ProtocolType.IP); socket.Blocking = false; //置socket非阻塞狀態(tài) socket.Bind(new IPEndPoint(IPAddress.Parse(IP), 0)); //綁定套接字 if (SetSocketOption()==false) error_occurred=true; } |
在CreateAndBindSocket函數(shù)中有一個自定義的SetSocketOption函數(shù),它和Socket類中的SetSocketOption不同,我們在這里定義的是具有IO控制功能的SetSocketOption,它的定義如下:
private bool SetSocketOption() //設置raw socket { bool ret_value = true; try { socket.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.HeaderIncluded, 1); byte []IN = new byte[4]{1, 0, 0, 0}; byte []OUT = new byte[4]; //低級別操作模式,接受所有的數(shù)據(jù)包,這一步是關鍵,必須把socket設成raw和IP Level才可用SIO_RCVALL int ret_code = socket.IOControl(SIO_RCVALL, IN, OUT); ret_code = OUT[0] + OUT[1] + OUT[2] + OUT[3];//把4個8位字節(jié)合成一個32位整數(shù) if(ret_code != 0) ret_value = false; } catch(SocketException) { ret_value = false; } return ret_value; } |
int WSAIoctl( SOCKET s, //一個指定的套接字 DWORD dwIoControlCode, //控制操作碼 LPVOID lpvInBuffer, //指向輸入數(shù)據(jù)流的指針 DWORD cbInBuffer, //輸入數(shù)據(jù)流的大小(字節(jié)數(shù)) LPVOID lpvOutBuffer, // 指向輸出數(shù)據(jù)流的指針 DWORD cbOutBuffer, //輸出數(shù)據(jù)流的大小(字節(jié)數(shù)) LPDWORD lpcbBytesReturned, //指向輸出字節(jié)流數(shù)目的實數(shù)值 LPWSAOVERLAPPED lpOverlapped, //指向一個WSAOVERLAPPED結構 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine//指向操作完成時執(zhí)行的例程 ); |
public bool ErrorOccurred { get { return error_occurred; } } |
//解析接收的數(shù)據(jù)包,形成PacketArrivedEventArgs事件數(shù)據(jù)類對象,并引發(fā)PacketArrival事件 unsafe private void Receive(byte [] buf, int len) { byte temp_protocol=0; uint temp_version=0; uint temp_ip_srcaddr=0; uint temp_ip_destaddr=0; short temp_srcport=0; short temp_dstport=0; IPAddress temp_ip; PacketArrivedEventArgs e=new PacketArrivedEventArgs();//新網(wǎng)絡數(shù)據(jù)包信息事件 fixed(byte *fixed_buf = buf) { IPHeader * head = (IPHeader *) fixed_buf;//把數(shù)據(jù)流整和為IPHeader結構 e.HeaderLength=(uint)(head->ip_verlen & 0x0F) << 2; temp_protocol = head->ip_protocol; switch(temp_protocol)//提取協(xié)議類型 { case 1: e.Protocol="ICMP"; break; case 2: e.Protocol="IGMP"; break; case 6: e.Protocol="TCP"; break; case 17: e.Protocol="UDP"; break; default: e.Protocol= "UNKNOWN"; break; } temp_version =(uint)(head->ip_verlen & 0xF0) >> 4;//提取IP協(xié)議版本 e.IPVersion = temp_version.ToString(); //以下語句提取出了PacketArrivedEventArgs對象中的其他參數(shù) temp_ip_srcaddr = head->ip_srcaddr; temp_ip_destaddr = head->ip_destaddr; temp_ip = new IPAddress(temp_ip_srcaddr); e.OriginationAddress =temp_ip.ToString(); temp_ip = new IPAddress(temp_ip_destaddr); e.DestinationAddress = temp_ip.ToString(); temp_srcport = *(short *)&fixed_buf[e.HeaderLength]; temp_dstport = *(short *)&fixed_buf[e.HeaderLength+2]; e.OriginationPort=IPAddress.NetworkToHostOrder(temp_srcport).ToString(); e.DestinationPort=IPAddress.NetworkToHostOrder(temp_dstport).ToString(); e.PacketLength =(uint)len; e.MessageLength =(uint)len - e.HeaderLength; e.ReceiveBuffer=buf; //把buf中的IP頭賦給PacketArrivedEventArgs中的IPHeaderBuffer Array.Copy(buf,0,e.IPHeaderBuffer,0,(int)e.HeaderLength); //把buf中的包中內(nèi)容賦給PacketArrivedEventArgs中的MessageBuffer Array.Copy(buf,(int)e.HeaderLength,e.MessageBuffer,0,(int)e.MessageLength); } //引發(fā)PacketArrival事件 OnPacketArrival(e); } |
public void Run() //開始監(jiān)聽 { IAsyncResult ar = socket.BeginReceive(receive_buf_bytes, 0, len_receive_buf, SocketFlags.None, new AsyncCallback(CallReceive), this); } |
private void CallReceive(IAsyncResult ar)//異步回調(diào) { int received_bytes; received_bytes = socket.EndReceive(ar); Receive(receive_buf_bytes, received_bytes); if (KeepRunning) Run(); } |
public delegate void PacketArrivedEventHandler(Object sender, PacketArrivedEventArgs args); //事件句柄:包到達時引發(fā)事件 public event PacketArrivedEventHandler PacketArrival;//聲明時間句柄函數(shù) |
public void Shutdown() //關閉raw socket { if(socket != null) { socket.Shutdown(SocketShutdown.Both); socket.Close(); } } |
新聞熱點
疑難解答
圖片精選