首页 > 开发 > 综合 > 正文

用c#监控网络流量

2024-07-21 02:29:18
字体:
来源:转载
供稿:网友
   以下的代码的原作是opensource的一个叫sniffer.net的,用vb.net写的,这里只是简单的用c#翻译了一下,暂时还只能监控所有数据包,不能监控某一个进程的数据包,代码如下:
using system;
using system.text;
using system.net;
using system.net.sockets;
using system.runtime.interopservices;

namespace updatetester
{
 /**//// <summary>
 /// monitor 的摘要说明。
 /// </summary>
 public class monitor
 {
  public delegate void newpacketeventhandler(monitor m, packet p);
  public event newpacketeventhandler newpacket;
  private socket m_monitor;
  private ipaddress m_ip;
  private byte[] m_buffer = new byte[65535];
  private const system.int32 ioc_vendor = 0x18000000;
  private const int ioc_in = -2147483648;
  private const int sio_rcvall = ioc_in ^ ioc_vendor ^ 1;
  private const int security_builtin_domain_rid = 0x20;
  private const int domain_alias_rid_admins = 0x220;

  public system.net.ipaddress ip
  {
   get { return m_ip; }
  }

  public byte[] buffer
  {
   get { return m_buffer; }
  }

  public monitor()
  {
   //
   // todo: 在此处添加构造函数逻辑
   //
  }

  public monitor(ipaddress ipaddress)
  {
   if (!(environment.osversion.platform == platformid.win32nt) && environment.osversion.version.major<5)
   {
    throw new notsupportedexception("this program requires windows 2000, windows xp or windows .net server!");
   }
   m_ip = ipaddress;
  }

  public void start()
  {
   if (m_monitor==null)
   {
    try
    {
     m_monitor = new socket(addressfamily.internetwork, sockettype.raw, protocoltype.ip);
     m_monitor.bind(new ipendpoint(ip, 0));
     m_monitor.iocontrol(sio_rcvall, bitconverter.getbytes(1), null);
     m_monitor.beginreceive(m_buffer, 0, m_buffer.length, socketflags.none, new asynccallback(onreceive), null);
    }
    catch (exception e)
    {
     m_monitor = null;
     throw new socketexception();
    }
   }
  }

  public void stop()
  {
   if (m_monitor!=null)
   {
    m_monitor.close();
   }
   m_monitor = null;
  }

  public void onreceive(system.iasyncresult ar)
  {
   try
   {
    int received = m_monitor.endreceive(ar);

    try
    {
     if (m_monitor!=null)
     {
      byte[] pkt = new byte[received];
      array.copy(buffer, 0, pkt, 0, received);
      onnewpacket(new packet(pkt, datetime.now));
     }
    }
    catch(exception e)
    {
     throw;
    }

    m_monitor.beginreceive(buffer, 0, buffer.length, socketflags.none, new asynccallback(onreceive), null);
   }
   catch (exception e)
   {

   }
  }

  protected void onnewpacket(packet p)
  {
   newpacket(this, p);
  }
 }
}


using system;
using system.text;
using system.net;
using system.net.sockets;

namespace updatetester
{

 public enum precedence
 {
  routine = 0,
  priority = 1,
  immediate = 2,
  flash = 3,
  flashoverride = 4,
  criticecp = 5,
  internetworkcontrol = 6,
  networkcontrol = 7
 }

 public enum delay
 {
  normaldelay = 0,
  lowdelay = 1
 }

 public enum throughput
 {
  normalthroughput = 0,
  highthroughput = 1
 }

 public enum reliability
 {
  normalreliability = 0,
  highreliability = 1
 }

 public enum protocol
 {
  ggp = 3,
  icmp = 1,
  idp = 22,
  igmp = 2,
  ip = 4,
  nd = 77,
  pup = 12,
  tcp = 6,
  udp = 17,
  other = -1
 }
 /**//// <summary>
 /// packet 的摘要说明。
 /// </summary>
 public class packet
 {

  private byte[] m_raw;
  private datetime m_time;
  private int m_version;
  private int m_headerlength;
  private precedence m_precedence;
  private delay m_delay;
  private throughput m_throughput;
  private reliability m_reliability;
  private int m_totallength;
  private int m_identification;
  private int m_timetolive;
  private protocol m_protocol;
  private byte[] m_checksum;
  private string m_sourceaddress;
  private string m_destinationaddress;
  private int m_sourceport;
  private int m_destinationport;

  public packet()
  {
   //
   // todo: 在此处添加构造函数逻辑
   //
  }
  //
  //  public packet(byte[] raw):(byte[] raw, datetime time)
  //  {
  //   packet(raw, datetime.now);
  //  }

  public packet(byte[] raw, datetime time)
  {
   if (raw==null)
   {
    throw new argumentnullexception();
   }
   if (raw.length<20)
   {
    throw new argumentexception();
   }

   this.m_raw = raw;
   this.m_time = time;
   this.m_headerlength = (raw[0] & 0xf) * 4;
   if ((raw[0] & 0xf) < 5) {throw new argumentexception();}
   this.m_precedence = (precedence)((raw[1] & 0xe0) >> 5);
   this.m_delay = (delay)((raw[1] & 0x10) >> 4);
   this.m_throughput = (throughput)((raw[1] & 0x8) >> 3);
   this.m_reliability = (reliability)((raw[1] & 0x4) >> 2);
   this.m_totallength = raw[2] * 256 + raw[3];
   if ( ! (this.m_totallength == raw.length)) { throw new argumentexception();} // invalid size of packet;
   this.m_identification = raw[4] * 256 + raw[5];
   this.m_timetolive = raw[8];

   m_protocol = (protocol)raw[9];

   m_checksum = new byte[2];
   m_checksum[0] = raw[11];
   m_checksum[1] = raw[10];

   try
   {
    m_sourceaddress = getipaddress(raw, 12);
    m_destinationaddress = getipaddress(raw, 16);
   }
   catch (exception e)
   {
    throw;
   }

   if (m_protocol == protocol.tcp || m_protocol == protocol.udp)
   {
    m_sourceport = raw[m_headerlength] * 256 + raw[m_headerlength + 1];
    m_destinationport = raw[m_headerlength + 2] * 256 + raw[m_headerlength + 3];
   }
   else
   {
               
    m_sourceport = -1;
    m_destinationport = -1;
   }
  }

  public string getipaddress(byte[] barray, int nstart)
  {
   byte[] tmp = new byte[4];

   if (barray.length > nstart + 2)
   {
    tmp[0] = barray[nstart];
    tmp[1] = barray[nstart + 1];
    tmp[2] = barray[nstart + 2];
    tmp[3] = barray[nstart + 3];
   }

   return tmp[0] + "." + tmp[1] + "." + tmp[2] + "." + tmp[3];
  }

  public int totallength
  {
   get { return m_totallength; }
  }

  public datetime time
  {
   get { return this.m_time; }
  }

  public protocol protocol
  {
   get { return this.m_protocol; }
  }

  public string sourceaddress
  {
   get { return this.m_sourceaddress; }
  }

  public string source
  {
   get
   {
    if ( m_sourceport != -1 )
    {
     return sourceaddress.tostring() + ":" + m_sourceport.tostring();
    }
    else
    {
     return sourceaddress.tostring();
    }
   }
  }

  public string destination
  {
   get
   {
    if (this.m_destinationport != -1)
    {
     return destinationaddress.tostring() + ":" + m_destinationport.tostring();
    }
    else
    {
     return destinationaddress.tostring();
     }
   }
  }

  public string destinationaddress
  {

   get
   {
    return m_destinationaddress;
   }
  }
 }
}

 

在主程序里
private monitor[] m_packetmonitors;
  private arraylist m_packets;
  private system.windows.forms.statusbar statusbar1;
  private int m_packetssize;

执行方法中
private void startmonitor()
  {
   ipaddress[] hosts = dns.resolve(dns.gethostname()).addresslist;

   if (hosts.length == 0) { throw new notsupportedexception("this computer does not have non-loopback interfaces installed!");}
   for (int i=0; i<hosts.length; i++)
   {
   }

   m_packetmonitors = new monitor[1];
   m_packets = new arraylist();
   m_packetmonitors[0] = new monitor(hosts[0]);

// 添加代理,每次有新的packet到时都出发下面哪个动作
   m_packetmonitors[0].newpacket+=new monitor.newpacketeventhandler(this.onnewpacket);
   m_packetmonitors[0].start();
  }

// 这个方法用于把packet显示到一个地方

private void onnewpacket(monitor m, packet p)
  {
   m_packets.add(p);
   m_packetssize += p.totallength;
   try
   {
    txtlog.text += p.time.tostring()+p.protocol.tostring()+p.source.tostring()+p.destination.tostring()+p.totallength.tostring();
 
   }
   catch (exception e)
   {
    messagebox.show(e.message);
   }

   statusbar1.text = string.format("intercepted {0} packet(s) [{1} bytes]", m_packets.count, m_packetssize);
  }


发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表