|
C#的IOControl函数不像WSAIoctl函数那么复杂,其中只包括其中的控制操作码、输入字节流、输出字节流三个参数,不过这三个参数已经足够了。我们看到函数中定义了一个字节数组:byte []IN = new byte[4]{1, 0, 0, 0}实际上它是一个值为1的DWORD或是Int32,同样byte []OUT = new byte[4];也是,它整和了一个int,作为WSAIoctl函数中参数lpcbBytesReturned指向的值。
因为设置套接字选项时可能会发生错误,需要用一个值传递错误标志:
public bool ErrorOccurred { get { return error_occurred; } }
下面的函数实现的数据包的接收:
//解析接收的数据包,形成PacketArrivedEventArgs事件数据类对象,并引发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();//新网络数据包信息事件
fixed(byte *fixed_buf = buf) { IPHeader * head = (IPHeader *) fixed_buf;//把数据流整和为IPHeader结构 e.HeaderLength=(uint)(head->ip_verlen & 0x0F) << 2;
temp_protocol = head->ip_protocol; switch(temp_protocol)//提取协议类型 { 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协议版本 e.IPVersion = temp_version.ToString();
//以下语句提取出了PacketArrivedEventArgs对象中的其他参数 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中的包中内容赋给PacketArrivedEventArgs中的MessageBuffer Array.Copy(buf,(int)e.HeaderLength,e.MessageBuffer,0,(int)e.MessageLength); } //引发PacketArrival事件 OnPacketArrival(e); }
上一页 [1] [2] [3] [4] 下一页
 【责编:Youping】 |