刚开始学,写个简单的sniffer可是就是测试不通过。。。? maxlength=

改了半天累了。还是没搞好,发上来大家一起看看吧。。是照着一本书写的

using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;

namespace SimpleSniff
{
    
/// <summary>
    
/// Form1 的摘要说明?1br/>    /// </summary>

    public class SniffWindow : System.Windows.Forms.Form
    
{
        
private System.Windows.Forms.PictureBox pictureBox1;
        
private System.Windows.Forms.ListBox resultListBox;
        
private System.Windows.Forms.Button startButton;
        
private System.Windows.Forms.Button stopButton;
        
private System.Windows.Forms.Button clearButton;
        
private System.Windows.Forms.ComboBox addressComboBox;
        
private System.Windows.Forms.Label label1;
        
private SniffSocket mySniffSocket;
        
/// <summary>
        
/// 必需的设计器变量?1br/>        /// </summary>

        private System.ComponentModel.Container components = null;

        
public SniffWindow()
        
{
            
//
            
// Windows 窗体设计器支持所必需?1br/>            //
            InitializeComponent();

            
//
            
// TODO: ?3#160;InitializeComponent 调用后添加任何构造函数代?1br/>            //
        }


        
/// <summary>
        
/// 清理所有正在使用的资源?1br/>        /// </summary>

        protected override void Dispose( bool disposing )
        
{
            
if( disposing )
            
{
                
if (components != null
                
{
                    components.Dispose();
                }

            }

            
base.Dispose( disposing );
        }


        
Windows Form Designer generated code

这是MainForm.cs
using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;

namespace SimpleSniff
{
    
/// <summary>
    
/// PacketDisplay 的摘要说明?1br/>    /// </summary>

    public class PacketDisplay : System.Windows.Forms.Form
    
{
        
private System.Windows.Forms.Label label6;
        
private System.Windows.Forms.Label label7;
        
private System.Windows.Forms.Label label8;
        
private System.Windows.Forms.Label label9;
        
private System.Windows.Forms.ListBox listBox1;
        
private System.Windows.Forms.Label src_addLabel;
        
private System.Windows.Forms.Label dest_addLabel;
        
private System.Windows.Forms.Label src_portLabel;
        
private System.Windows.Forms.Label dest_portLabel;
        
private System.Windows.Forms.Label protocolLabel;
        
/// <summary>
        
/// 必需的设计器变量?1br/>        /// </summary>

        private System.ComponentModel.Container components = null;

        
public PacketDisplay(SniffSocket.PacketArrivedEventArgs e)
        
{
            
//
            
// Windows 窗体设计器支持所必需?1br/>            //
            InitializeComponent();
            src_addLabel.Text 
=e.OriginationAddress ;
            dest_addLabel.Text 
=e.DestinationAddress ;
            src_portLabel.Text 
=e.OriginationPort ;
            dest_portLabel.Text 
=e.DestinationPort ;
            protocolLabel.Text 
=e.Protocol ;
            
int x=0;
            
int y=0;
            
foreach (byte b in e.MessageBuffer )
            
{
                
if(x==0)
                    listBox1.Items .Add (b.ToString (
"x"+ "\t");
                
else
                    listBox1.Items [y]
+=(b.ToString ("x"+ "\t");
                x
++;
                
if (x>8)
                
{
                    x
=0;
                    y
++;

                }

            }


            
//
            
// TODO: ?3#160;InitializeComponent 调用后添加任何构造函数代?1br/>            //
        }


        
/// <summary>
        
/// 清理所有正在使用的资源?1br/>        /// </summary>

        protected override void Dispose( bool disposing )
        
{
            
if( disposing )
            
{
                
if(components != null)
                
{
                    components.Dispose();
                }

            }

            
base.Dispose( disposing );
        }


        
Windows Form Designer generated code

        
    }

}


PacketDisplay.cs

using System;
using System.Net;
using System.Net.Sockets;
using System.Runtime.InteropServices;

namespace SimpleSniff
{
    
/// <summary>
    
/// SniffSocket 的摘要说明?1br/>    /// </summary> 

    [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;
        [FieldOffset(
6)] public ushort ip_offer;
        [FieldOffset(
8)] public byte ip_ttl;
        [FieldOffset(
9)] public byte ip_protocol;
        [FieldOffset(
10)] public ushort ip_checksum;
        [FieldOffset(
12)] public uint ip_srcaddr;
        [FieldOffset(
16)] public uint ip_destaddr;
    }


    
public class SniffSocket
    
{
        
private bool keepRunning;
        
private static int rcv_buf_len;
        
private byte[] rcv_but_bytes;
        
private Socket socket=null;
        
private IAsyncResult ar;
        
public SniffSocket()
        
{
            
//
            
// TODO: 在此处添加构造函数逻辑
            
//
            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.Blocking 
= false;
            socket.Bind (
new IPEndPoint (IPAddress.Parse (IP),0));
            SetSocketOption();
        }

        
private void SetSocketOption()
        
{
            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_RCVALL=unchecked ((int)0x98000001);
                
int ret_code=socket.IOControl (SIO_RCVALL,IN,OUT);
                ret_code
=OUT[0]+OUT[1]+OUT[2]+OUT[3];
                
if (ret_code!=0)
                
{
                    ex
=new SniffSocketException ("command execute error");
                    
throw ex;
                }

            }

            
catch (SocketException e)
            
{
                ex
=new SniffSocketException ("socket error",e);
                
throw ex;
            }

        }

        
public void ShutDown()
        
{
            
if (socket!=null)
            
{
                socket.Shutdown (SocketShutdown.Both );
            }

        }

        
public void Run()
        
{
            IAsyncResult ar
= socket.BeginReceive (rcv_buf_bytes,0,riv_buf_len,SocketFlags.None ,new AsyncCallback (CallReceive),this);

        }

        
private void CallReceive(IAsyncResult ar)
        
{
            
int received_bytes;
            received_bytes 
= socket.EndReceive (ar);
            Receive(rcv_but_bytes,received_bytes);
            
if (keepRunning) Run();
 
        }

        
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_detport=0;
            IPAddress temp_ip;
            PacketArrivedEventArgs e
=new PacketArrivedEventArgs ();
            
fixed (byte *fixed_buf =buf)
            
{
                IPHeader 
* head = (IPHeader *) fixed_buf;
                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;
                e.IPVersion 
= temp_version.ToString ();

                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;
                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 protocol;
            
private string destination_port;
            
private string origination_port;
            
private string destination_address;
            
private string origination_address;
            
private string ip_version;
            
private uint total_packet_length;
            
private uint message_length;
            
private uint header_lenght;
            
private byte []receive_buf_bytes = null;
            
private byte []ip_header_bytes = null;
            
private byte []message_bytes = null;
            
public PacketArrivedEventArgs()
            
{
                
this.protocol = "";
                
this.destination_port = "";
                
this.origination_port = "";
                
this.destination_address = "";
                
this.origination_address = "";
                
this.ip_version = "";

                
this.total_packet_length = 0;
                
this.message_length = 0;
                
this.header_lenght = 0;

                
this.receive_buf_bytes =new byte[rcv_buf_len];
                
this.ip_header_bytes =new byte[rcv_buf_len];
                
this.message_bytes =new byte[riv_buf_len];
            }

            
public string Protocol
            
{
                
get {return protocol;}
                
set {protocol=value;}
            }

            
public string DestinationPort
            
{
                
get {return origination_port;}
                
set {destination_port=value;}
            }

            
public string OriginationPort
            
{
                
get {return origination_port;}
                
set {origination_port=value;}
            }

            
public string DestinationAddress
            
{
                
get {return destination_address;}
                
set {destination_address=value;}
            }

            
public string OriginationAddress
            
{
                
get {return origination_address;}
                
set {origination_address=value;}
            }

            
public string IPVersion
            
{
                
get {return ip_version;}
                
set {ip_version=value;}
            }

            
public uint PacketLength
            
{
                
get {return total_packet_length;}
                
set {total_packet_length=value;}
            }

            
public uint MessageLength
            
{
                
get {return message_length;}
                
set {message_lenght=value;}
            }

            
public uint HeaderLength
            
{
                
get {return header_length;}
                
set {header_length=value;}
            }

            
public byte [] ReceiveBuffer
            
{
                
get {return receive_buf_bytes;}
                
set {receive_buf_bytes=value;}
            }

            
public byte [] IPHeaderBuffer
            
{
                
get {return ip_header_buffer;}
                
set {ip_header_buffer=value;}
            }

            
public byte [] MessageBuffer
            
{
                
get {return message_bytes;}
                
set {message_bytes=value;}
            }

            
public override string ToString()
            
{
                
return protocol+origination_address + "\t" + 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);

            }

        }


        
public class SniffSocketException:Exception
        
{
            
public SniffSocketException():base()
            
{}
            
public SniffSocketException(string message):base(message)
            
{}
            
public SniffSocketException(string message,Exception innerException):base(message,innerException)
            
{}
        }

        
    }

}

SniffSocket
下面还有一?1br/>
using System;
using System.Windows.Forms;

namespace SimpleSniff
{
    
/// <summary>
    
/// App 的摘要说明?1br/>    /// </summary>

    public class App
    
{    
            
//
            
// TODO: 在此处添加构造函数逻辑
            
//
            [STAThread]
            
public static void Main()
            
{
                
try
                
{
                    SniffWindow mainWindow
= new SniffWindow();
                    Application.Run (mainWindow);
                }

                
catch(Exception ex)
                
{
                    MessageBox.Show (ex.ToString ()
+"\n\n"+ex.Message ,"ErrorOccured!");
                }

            }

    }

}


这是App.cs
using System.Reflection;
using System.Runtime.CompilerServices;//注意加了这个引用..

//
// 有关程序集的常规信息是通过下列 
//属性集控制的。更改这些属性值可修改与程序集
//关联的信息?1br/>//
[assembly: AssemblyTitle("")]
[assembly: AssemblyDescription(
"")]
[assembly: AssemblyConfiguration(
"")]
[assembly: AssemblyCompany(
"")]
[assembly: AssemblyProduct(
"")]
[assembly: AssemblyCopyright(
"")]
[assembly: AssemblyTrademark(
"")]
[assembly: AssemblyCulture(
"")]        

//
// 程序集的版本信息包含下列 4 个值:
//
//      主版?1br/>//      次版?1br/>//      内部版本?1br/>//      修订?1br/>//
// 您可以指定所有值,或使?3#8220;修订?3#8221;?3#8220;内部版本?3#8221;的默认值,方法为按如下方式 
// 使用*?1/SPAN>

[assembly: AssemblyVersion(
"1.0.*")]

//
// 要对程序集进行签名,必须指定要使用的密钥。有关程序集签名的更多信息,请参?3#160;
// Microsoft .NET 框架文档?1br/>//
// 使用下面的属性控制用于签名的密钥?1br/>//
// 注意?1br/>//   (*) 如果未指定密钥,则程序集不会被签名?1br/>//   (*) KeyName 是指已经安装在计算机上的
//      加密服务提供程序 (CSP) 中的密钥。KeyFile 是指包含
//       密钥的文件?1br/>//   (*) 如果 KeyFile ?3#160;KeyName 值都已指定,?3#160;
//       发生下列处理?1br/>//       (1) 如果?3#160;CSP 中可以找?3#160;KeyName,则使用该密钥?1br/>//       (2) 如果 KeyName 不存在?3#160;KeyFile 存在,则 
//           KeyFile 中的密钥安装?3#160;CSP 中并且使用该密钥?1br/>//   (*) 要创?3#160;KeyFile,可以使?3#160;sn.exe(强名称)实用工具?1br/>//       在指?3#160;KeyFile 时,KeyFile 的位置应该相对于
//       项目输出目录,即
//       %Project Directory%\obj\<configuration>。例如,如果 KeyFile 位于
//       该项目目录,应将 AssemblyKeyFile 
//       属性指定为 [assembly: AssemblyKeyFile("..\\..\\mykey.snk")]
//   (*) 延迟签名是一个高级选项 - 有关它的更多信息,请参阅 Microsoft .NET 框架
//       文档?1br/>//
[assembly: AssemblyDelaySign(false)]
[assembly: AssemblyKeyFile(
"")]
[assembly: AssemblyKeyName(
"")]
这是MainForm.csPacketDisplay.csSniffSocket下面还有一?1br/> 这是App.cs
posted @ 2004-12-03 20:09  SCADA组态软件(2D,3D)  阅读(990)  评论(2编辑  收藏  举报