当前位置:文档之家› 解析IP数据报

解析IP数据报

郑州轻工业学院网络协议分析课程设计题目:解析IP数据包姓名:院(系):计算机与通信工程学院专业班级:网络工程08-1学号:200807030140指导教师:成绩:时间:2011年6月12日至2011年6月17日郑州轻工业学院课程设计任务书题目解析IP数据包专业、班级网络工程08-1学号 200807030140姓名主要内容、基本要求、主要参考资料等:主要内容:捕获网络中的IP数据包,解析数据包的内容,显示结果,并将结果写入日志文件。

设置停止标志,当程序接收到停止命令时即停止。

基本要求:使用图形界面实现IP数据包的解析,画出基本流程图,写出解析的实现过程、操作演示截图与核心代码。

参考资料:《计算机网络(第5版)》谢希仁电子工业出版社《网络协议分析》寇晓蕤、罗军勇等机械工业出版社《TCP/IP协议族(第4版)》王海、张娟等译清华大学出版社《c#高级编程(第6版)》李铭译清华大学出版社《Visual C#.NET网络核心编程》周存杰清华大学出版社完成期限:指导教师签名:课程负责人签名:2011年 6 月 16 日目录一实验目的 (4)二实验内容 (4)三实验环境 (4)四实验步骤 (4)1.实验流程图 (4)2.实验核心代码 (5)3.演示截图 (6)五实验体会 (7)六参考文献 (7)七附录 (7)Socket.cs (7)CatchIP.cs (10)ShowIP.cs (11)一实验目的熟悉IP包结构,加深对IP层工作原理的理解和认识。

二实验内容(1)捕获网络中的IP数据包,解析数据包的内容,显示结果,并将结果写入日志文件。

(2)显示的内容包括:捕获的IP包的版本、头长度、服务类型、数据包总长度、数据包标识、分段标志、分段偏移值、生存时间、上层协议类型、头校验和、源IP地址和目的IP地址等内容。

(3)设置停止标志,当程序接收到停止命令时即停止。

三实验环境本实验所使用的编程语言为c#程序语言实验开发环境为Microsoft Visual Studio 2008四实验步骤1.实验流程图2.实验核心代码1)公共类中的核心代码2)捕获IP信息窗口核心代码3)显示窗口核心代码3.演示截图五实验体会哈哈….这东西自己写啦哈哈哈……六参考文献《计算机网络(第5版)》谢希仁电子工业出版社《网络协议分析》寇晓蕤、罗军勇等机械工业出版社《TCP/IP协议族(第4版)》王海、张娟等译清华大学出版社《c#高级编程(第6版)》李铭译清华大学出版社《Visual C#.NET网络核心编程》周存杰清华大学出版社七附录Socket.csnamespace GetIp{[StructLayout(LayoutKind.Explicit)]public struct IPHeader{[FieldOffset(0)] public byte ip_verlen; //首部长度+版本号[FieldOffset(1)] public byte ip_tos; //服务类型[FieldOffset(2)] public ushort ip_totallength; //数据包总长度)[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位协议(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地址}public class Sock{private bool keepRunning;private static int rcv_buf_len;private byte[] rcv_buf_bytes;private Socket socket = null;//声明套接字public Sock(){ rcv_buf_len=4096;rcv_buf_bytes=new byte [rcv_buf_len];}public bool KeepRunning{ get{return keepRunning;}set{keepRunning=value;}}public void CreateAndBindSocket(string IP) //建立并绑定套接字{socket=new Socket (AddressFamily.InterNetwork ,SocketType.Raw ,ProtocolType.IP );socket.Bind(new IPEndPoint(IPAddress.Parse(IP), 0));SetSocketOption();}private void SetSocketOption() //Socket设置{ SniffSocketException ex;try{socket.SetSocketOption (SocketOptionLevel.IP ,SocketOptionName.HeaderIncluded ,1);byte[] IN=new byte [4]{1,0,0,0};byte[] OUT = new byte[4]; //低级别操作模式,接受所有的数据包int SIO_RCV ALL = unchecked((int)0x98000001);int ret_code=socket.IOControl (SIO_RCV ALL,IN,OUT);ret_code = OUT[0] + OUT[1] + OUT[2] + OUT[3];if(ret_code!=0){ ex=new SniffSocketException ("命令实行错误!!");throw ex;}}catch(SocketException e){ ex=new SniffSocketException ("创建套接字错误!!",e);throw ex;}}public void ShutDown() //关闭接收{ if(socket!=null){ socket.Shutdown(SocketShutdown.Both); }}public void Run(){ IAsyncResult ar = socket.BeginReceive(rcv_buf_bytes, 0, rcv_buf_len, SocketFlags.None, new AsyncCallback(CallReceive), this); }private void CallReceive(IAsyncResult ar) //连续接受数据{ int received_bytes;received_bytes = socket.EndReceive(ar);Receive(rcv_buf_bytes, received_bytes);if (keepRunning) Run();}unsafe private void Receive(byte [] buf, int len) //接受IP数据包信息方法{ byte temp_ip_tos = 0;byte temp_protocol=0; //提取协议类型uint temp_version=0; //提取IP协议版本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;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;}e.HeaderLength=(uint)(head->ip_verlen & 0x0F) << 2;e.TTL = (uint)head->ip_ttl;e.IPTos = ((uint)head->ip_tos).ToString();e.Packet_id = ((ushort)head->ip_id).ToString();e.Packet_set = ((ushort)((head->ip_offset) >> 13)).ToString();e.Ip_check=((ushort)head->ip_checksum&(0X1FFF)).ToString();temp_version = (uint)(head->ip_verlen & 0xF0) >> 4;e.IPVersion = temp_version.ToString();temp_ip_tos = head->ip_tos;temp_ip_srcaddr = head->ip_srcaddr;temp_ip = new IPAddress(temp_ip_srcaddr);e.OriginationAddress =temp_ip.ToString();temp_ip_destaddr = head->ip_destaddr;temp_ip = new IPAddress(temp_ip_destaddr);e.DestinationAddress = temp_ip.ToString();temp_srcport = *(short *)&fixed_buf[e.HeaderLength];e.OriginationPort=((ushort)workToHostOrder(temp_srcport)).ToString();temp_dstport = *(short*)&fixed_buf[e.HeaderLength + 2];e.DestinationPort=((ushort)workToHostOrder(temp_dstport)).ToString();e.PacketLength =(uint)len;e.MessageLength =(uint)len - e.HeaderLength;e.ReceiveBuffer=buf;Array.Copy(buf,0,e.IPHeaderBuffer,0,(int)e.HeaderLength);Array.Copy(buf,(int)e.HeaderLength,e.MessageBuffer,0,(int)e.MessageLength);}OnPacketArrival(e);}public class PacketArrivedEventArgs : EventArgs{ private string ip_tos;private string protocol;private string destination_port;private string origination_port;private string destination_address;private string origination_address;private string ip_version; //IP版本号private uint total_packet_length;//IP总长度private uint message_length;private uint header_length;private string packet_ip_id;private string packet_ip_set;private string ip_check_he;private uint ipttl;private byte []receive_buf_bytes = null;private byte []ip_header_bytes = null;private byte []message_bytes = null;public string Ip_check //校验和{ get { return ip_check_he; }set { ip_check_he = value; }}下定义同,略…public override string ToString() //重载输出格式{return " " + protocol + " " + origination_address + " " + destination_address;}}public delegate void PacketArrivedEventHandler(Object sender, PacketArrivedEventArgs args);public event PacketArrivedEventHandler PacketArrival; //声明时间句柄函数protected virtual void OnPacketArrival(PacketArrivedEventArgs e){ if (PacketArrival != null){PacketArrival(this, e);}}}}CatchIP.csnamespace GetIp{public class MyWindow : System.Windows.Forms.Form{ public MyWindow() //初始化{InitializeComponent();}private void InitializeComponent() //自定义初始化函数{ 略……}private void MyWindow_Load(object sender, System.EventArgs e) //加载{ManagementObjectSearcher query1 = new ManagementObjectSearcher("SELECT * FROM Win32_NetworkAdapterConfiguration");ManagementObjectCollection queryCollection1 = query1.Get();string[] IPString = new string[10];int x = 0;string[] temp;foreach (ManagementObject mo in queryCollection1){ temp = mo["IPAddress"] as string[];if (temp != null){ foreach (string st in temp) //捕获所有的IP{ IPString[x] = st;if (st != "") { addressComboBox.Items.Add(st); }x++;}}}addressComboBox.Text = addressComboBox.Items[0] as string;mySniffSocket = new Sock();try{ mySniffSocket.CreateAndBindSocket(addressComboBox.Text.Trim());}catch (Sock.SniffSocketException ex){ MessageBox.Show(this, ex.Message);}mySniffSocket.PacketArrival+=newSock.PacketArrivedEventHandler(DataArrival ); }private void DataArrival(Object sender, Sock.PacketArrivedEventArgs e){ try{ resultListBox.Items.Add(e); }catch (Exception e1) { MessageBox.Show(e1.ToString()); }}protected override void Dispose(bool disposing)if( disposing ){if (components != null){ components.Dispose();}}base.Dispose( disposing );}private void startButton_Click(object sender, System.EventArgs e) //开始捕获{ if(mySniffSocket.KeepRunning==false){ mySniffSocket.KeepRunning =true;try{ mySniffSocket.Run ();}catch(SocketException){mySniffSocket.CreateAndBindSocket (addressComboBox.Text );mySniffSocket.Run ();}startButton.Text ="暂停";}else{ mySniffSocket.KeepRunning =false;startButton.Text ="继续";}}private void stopButton_Click(object sender, System.EventArgs e) //停止捕获{ mySniffSocket.KeepRunning =false;startButton.Text ="开始";Thread.Sleep (10);mySniffSocket.ShutDown ();}private void clearButton_Click(object sender, System.EventArgs e) //清除列表{resultListBox.Items.Clear(); }private void resultListBox_DoubleClick(object sender, System.EventArgs e) {ShowIpdlg=newShowIp(resultListBox.SelectedItemasSock.PacketArrivedEventArgs);dlg.Show();}private void button1_Click(object sender, EventArgs e) //退出{if (MessageBox.Show("你确定要退出本程序吗?", "提醒", MessageBoxButtons.OKCancel, rmation, MessageBoxDefaultButton.Button1) == DialogResult.OK)Application.Exit();}}}ShowIP.csnamespace GetIp{ public class ShowIp : System.Windows.Forms.Form{ public ShowIp(){InitializeComponent();}private void InitializeComponent() //自定义初始化{略… }private string BytesToString(byte[] bTemp)//将字节数组转化成字符串{ int bLen = bTemp.Length;string rtnString = "";for (int i = 0; i < bLen; i++)rtnString += bTemp[i].ToString();return rtnString;}public ShowIp(Sock.PacketArrivedEventArgs e):this(){ src_addLabel.Text =e.OriginationAddress ; //源地址dest_addLabel.Text =e.DestinationAddress ; //目的地址src_portLabel.Text =e.OriginationPort; //源端口dest_portLabel.Text =e.DestinationPort; //目的端口protocolLabel.Text =e.Protocol; //协议类型label8.Text = e.HeaderLength.ToString()+" byte"; //IP包头长度label9.Text = e.PacketLength.ToString()+" byte"; //IP总长度label12.Text = e.MessageLength.ToString()+" byte"; //IP数据包长度label13.Text =e.TTL.ToString()+" hops"; //生存时间label15.Text = e.IPVersion; //IP版本号label17.Text = e.IPTos.ToString(); //服务类型label19.Text = e.Packet_id; //IP标识label21.Text = e.Packet_set; //IP标志label23.Text = e.Ip_check; //首部校验和}protected override void Dispose(bool disposing){ if (disposing){if (components != null){components.Dispose();}}base.Dispose(disposing);}private string getstring() //信息合并,以便输出到文件{ string str_contant;str_contant="IP版本号: "+label15.Text.ToString()+Environment.NewLine;str_contant += "总长度: " + label9.Text.ToString() + Environment.NewLine;下同,略…return str_contant;}private void IO_out() //输出信息到日志文件{ string path = @"D:\log_ip.log";string text=getstring();try{ FileStream fs_W = new FileStream(path, FileMode.Create);StreamWriter sw = new StreamWriter(fs_W);sw.Write(text);sw.Close();MessageBox.Show("写入日志完毕!\n");}catch(IOException ex){ MessageBox.Show (ex.ToString ()+"\n\n"+ex.Message,"写入日志错误!");}}}说明:由于代码过长,本报告只贴出了代码中关键的部分,而对于如控件的初始化等代码全部省略说明1、课程设计进行期间,学生应按教学计划,将每天的学习情况(包括学习内容、遇到问题及解决办法、心得体会等)如实进行记录。

相关主题