在好例子网,分享、交流、成长!
您当前所在位置:首页C# 开发实例C#网络编程 → c# 写的网络嗅探器示例源码下载

c# 写的网络嗅探器示例源码下载

C#网络编程

下载此实例
  • 开发语言:C#
  • 实例大小:0.03M
  • 下载次数:74
  • 浏览次数:605
  • 发布时间:2013-11-18
  • 实例类别:C#网络编程
  • 发 布 人:crazycode
  • 文件格式:.rar
  • 所需积分:2
 相关标签: C# 网络

实例介绍

【实例简介】

【实例截图】

【核心代码】

using System;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.Runtime.InteropServices;
using System.Collections;
using System.Collections.Specialized;

namespace sniffer
{
	/// <summary>
	/// A class that intercepts IP packets on a specific interface.
	/// </summary>
	/// <remarks>
	/// This class only works on Windows 2000 and higher.
	/// </remarks>
	public class PacketMonitor 
	{
		/// <summary>
		/// Holds all the listeners for the NewPacket event.
		/// </summary>
		public event NewPacketEventHandler NewPacket;
		// private variables
		private Socket m_Monitor;
		private IPAddress m_IP;
		private byte[] m_Buffer;
		private const int IOC_VENDOR = 0x18000000;
		private const int IOC_IN = -2147483648; //0x80000000; /* copy in parameters */
		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;

		/// <summary>
		/// Initializes a new instance of the PacketMonitor class.
		/// </summary>
		/// <param name="ip">The interface on which to listen for IP packets.</param>
		/// <exception cref="NotSupportedException">The operating system does not support intercepting packets.</exception>
		public PacketMonitor(IPAddress ip) 
		{
			// make sure the user runs this program on Windows NT 5.0 or higher
			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!");
			// make sure the user is an Administrator
			if (!IsUserAnAdmin())
				throw new NotSupportedException("This program can only be run by administrators!");
			m_IP = ip;
			m_Buffer = new byte[65535];
		}
		/// <summary>
		/// Cleans up the unmanaged resources.
		/// </summary>
		~PacketMonitor() 
		{
			Stop();
		}
		/// <summary>
		/// Starts listening on the specified interface.
		/// </summary>
		/// <exception cref="SocketException">An error occurs when trying to intercept IP packets.</exception>
		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((int)1), null);
					m_Monitor.BeginReceive(m_Buffer, 0, m_Buffer.Length, SocketFlags.None, new AsyncCallback(this.OnReceive), null);
				} 
				catch 
				{
					m_Monitor = null;
					throw new SocketException();
				}
			}
		}
		/// <summary>
		/// Stops listening on the specified interface.
		/// </summary>
		public void Stop() 
		{
			if (m_Monitor != null) 
			{
				m_Monitor.Close();
				m_Monitor = null;
			}
		}
		/// <summary>
		/// Called when the socket intercepts an IP packet.
		/// </summary>
		/// <param name="ar">The asynchronous result.</param>
		private void OnReceive(IAsyncResult ar) 
		{
			try 
			{
				int received = m_Monitor.EndReceive(ar);
				try 
				{
					if (m_Monitor != null) 
					{
						byte[] packet = new byte[received];
						Array.Copy(Buffer, 0, packet, 0, received);
						OnNewPacket(new Packet(packet));
					}
				} 
				catch {} // invalid packet; ignore
				m_Monitor.BeginReceive(Buffer, 0, Buffer.Length, SocketFlags.None, new AsyncCallback(this.OnReceive), null);
			} 
			catch 
			{
				Stop();
			}
		}
		/// <summary>
		/// The interface used to intercept IP packets.
		/// </summary>
		/// <value>An <see cref="IPAddress"/> instance.</value>
		public IPAddress IP 
		{
			get 
			{
				return m_IP;
			}
		}
		/// <summary>
		/// The buffer used to store incoming IP packets.
		/// </summary>
		/// <value>An array of bytes.</value>
		protected byte[] Buffer 
		{
			get 
			{
				return m_Buffer;
			}
		}
		/// <summary>
		/// Raises an event that indicates a new packet has arrived.
		/// </summary>
		/// <param name="p">The arrived <see cref="Packet"/>.</param>
		protected void OnNewPacket(Packet p) 
		{
			bool AllowPacket = true;
			string tempStr = "";
			int tPort = 0;

			// filter packets coming from this IP
			if (FilterSourceIP.Count > 0)
			{
				AllowPacket = false;
				tempStr = p.Source;
				foreach (string fIP in FilterSourceIP)
				{
					if (fIP.Length > 0)
						if (tempStr.Substring(0, fIP.Length).CompareTo(fIP) == 0)
						{
							AllowPacket = true;
							break; // we found a match
						}
				}
			}

			// if the packet did not match a filter, exit
			if (! AllowPacket)
				return;

			// filter packets going to this IP
			if (FilterDestIP.Count > 0)
			{
				AllowPacket = false;
				tempStr = p.Destination;
				foreach (string dIP in FilterDestIP)
				{
					if (dIP.Length > 0)
						if (tempStr.Substring(0, dIP.Length).CompareTo(dIP) == 0)
						{
							AllowPacket = true;
							break; // we found a match
						}
				}
			}

			// if the packet did not match a filter, exit
			if (! AllowPacket)
				return;

			// filter packets coming from this port
			if (FilterSourcePort.Count > 0)
			{
				AllowPacket = false;
				tPort = p.SourcePort;
				foreach (string sPort in FilterSourcePort)
				{
					if (sPort.Length > 0)
						if (tPort == System.Convert.ToInt32(sPort))
						{
							AllowPacket = true;
							break; // we found a match
						}
				}
			}

			// if the packet did not match a filter, exit
			if (! AllowPacket)
				return;

			// filter packets going to this port
			if (FilterDestPort.Count > 0)
			{
				AllowPacket = false;
				tPort = p.DestinationPort;
				foreach (string dPort in FilterSourcePort)
				{
					if (dPort.Length > 0)
						if (tPort == System.Convert.ToInt32(dPort))
						{
							AllowPacket = true;
							break; // we found a match
						}
				}
			}

			// if the packet did not match a filter, exit
			if (! AllowPacket)
				return;

			// raise the NewPacket event
			if (NewPacket != null)
				NewPacket(this, p);
		}

		/// <summary>
		/// if set, only shows packets which are sent from this IP
		/// Example: If you want to filter the 112.123.4.X, send 112.123.4.
		/// If you want to filter 112.X.X.X, send 112.
		/// If you want to filter 112.123.4.5, send 112.123.4.5
		/// </summary>
		public StringCollection FilterSourceIP = new StringCollection();

		/// <summary>
		/// if set, only shows packets which go to this IP
		/// Example: If you want to filter the 112.123.4.X, send 112.123.4.
		/// If you want to filter 112.X.X.X, send 112.
		/// If you want to filter 112.123.4.5, send 112.123.4.5
		/// </summary>
		public StringCollection FilterDestIP = new StringCollection();

		/// <summary>
		/// If set, only shows packets which come from this port 
		/// </summary>
		public StringCollection FilterSourcePort = new StringCollection();

		/// <summary>
		/// If set, only shows packets which go to this port
		/// </summary>
		public StringCollection FilterDestPort = new StringCollection();

		/// <summary>
		/// Tests whether the current user is a member of the Administrator's group.
		/// </summary>
		/// <returns>Returns <b>true</b> if the user is a member of the Administrator's group, <b>false</b> if not.</returns>
		private bool IsUserAnAdmin() 
		{ 
			byte[] NtAuthority = new byte[6];
			NtAuthority[5] = 5; // SECURITY_NT_AUTHORITY
			IntPtr AdministratorsGroup;
			int ret = AllocateAndInitializeSid(NtAuthority, 2, SECURITY_BUILTIN_DOMAIN_RID, DOMAIN_ALIAS_RID_ADMINS, 0, 0, 0, 0, 0, 0, out AdministratorsGroup); 
			if (ret != 0) 
			{
				if (CheckTokenMembership(IntPtr.Zero, AdministratorsGroup, ref ret) == 0) 
				{
					ret = 0;
				} 
				FreeSid(AdministratorsGroup); 
			}

			return (ret != 0);
		}
		/// <summary>
		/// The AllocateAndInitializeSid function allocates and initializes a security identifier (SID) with up to eight subauthorities.
		/// </summary>
		/// <param name="pIdentifierAuthority">Pointer to a SID_IDENTIFIER_AUTHORITY structure, giving the top-level identifier authority value to set in the SID.</param>
		/// <param name="nSubAuthorityCount">Specifies the number of subauthorities to place in the SID. This parameter also identifies how many of the subauthority parameters have meaningful values. This parameter must contain a value from 1 to 8.</param>
		/// <param name="dwSubAuthority0">Subauthority value to place in the SID.</param>
		/// <param name="dwSubAuthority1">Subauthority value to place in the SID.</param>
		/// <param name="dwSubAuthority2">Subauthority value to place in the SID.</param>
		/// <param name="dwSubAuthority3">Subauthority value to place in the SID.</param>
		/// <param name="dwSubAuthority4">Subauthority value to place in the SID.</param>
		/// <param name="dwSubAuthority5">Subauthority value to place in the SID.</param>
		/// <param name="dwSubAuthority6">Subauthority value to place in the SID.</param>
		/// <param name="dwSubAuthority7">Subauthority value to place in the SID.</param>
		/// <param name="pSid">Pointer to a variable that receives the pointer to the allocated and initialized SID structure.</param>
		/// <returns>If the function succeeds, the return value is nonzero. If the function fails, the return value is zero. To get extended error information, call GetLastError.</returns>
		[DllImport("advapi32.dll")]
		private extern static int AllocateAndInitializeSid(byte[] pIdentifierAuthority, byte nSubAuthorityCount, int dwSubAuthority0, int dwSubAuthority1, int dwSubAuthority2, int dwSubAuthority3, int dwSubAuthority4, int dwSubAuthority5, int dwSubAuthority6, int dwSubAuthority7, out IntPtr pSid);
		/// <summary>
		/// The CheckTokenMembership function determines whether a specified SID is enabled in an access token.
		/// </summary>
		/// <param name="TokenHandle">Handle to an access token. The handle must have TOKEN_QUERY access to the token. The token must be an impersonation token.</param>
		/// <param name="SidToCheck">Pointer to a SID structure. The CheckTokenMembership function checks for the presence of this SID in the user and group SIDs of the access token.</param>
		/// <param name="IsMember">Pointer to a variable that receives the results of the check. If the SID is present and has the SE_GROUP_ENABLED attribute, IsMember returns TRUE; otherwise, it returns FALSE.</param>
		/// <returns>If the function succeeds, the return value is nonzero. If the function fails, the return value is zero. To get extended error information, call GetLastError.</returns>
		[DllImport("advapi32.dll")]
		private extern static int CheckTokenMembership(IntPtr TokenHandle, IntPtr SidToCheck, ref int IsMember);
		/// <summary>
		/// The FreeSid function frees a security identifier (SID) previously allocated by using the AllocateAndInitializeSid function.
		/// </summary>
		/// <param name="pSid">Pointer to the SID structure to free.</param>
		/// <returns>This function does not return a value.</returns>
		[DllImport("advapi32.dll")]
		private extern static IntPtr FreeSid(IntPtr pSid);
		// <summary>
		// Tests whether the current user is a member of the Administrator's group.
		// </summary>
		// <returns>Returns TRUE if the user is a member of the Administrator's group, FALSE if not.</returns>
		//[DllImport("shell32.dll")]
		//private extern static int IsUserAnAdmin();
	}
	/// <summary>
	/// Represents the method that will handle the NewPacket event.
	/// </summary>
	/// <param name="pm">The <see cref="PacketMonitor"/> that intercepted the <see cref="Packet"/>.</param>
	/// <param name="p">The newly arrived <see cref="Packet"/>.</param>
	public delegate void NewPacketEventHandler(PacketMonitor pm, Packet p);
}

标签: C# 网络

实例下载地址

c# 写的网络嗅探器示例源码下载

不能下载?内容有错? 点击这里报错 + 投诉 + 提问

好例子网口号:伸出你的我的手 — 分享

网友评论

发表评论

(您的评论需要经过审核才能显示)

查看所有0条评论>>

小贴士

感谢您为本站写下的评论,您的评论对其它用户来说具有重要的参考价值,所以请认真填写。

  • 类似“顶”、“沙发”之类没有营养的文字,对勤劳贡献的楼主来说是令人沮丧的反馈信息。
  • 相信您也不想看到一排文字/表情墙,所以请不要反馈意义不大的重复字符,也请尽量不要纯表情的回复。
  • 提问之前请再仔细看一遍楼主的说明,或许是您遗漏了。
  • 请勿到处挖坑绊人、招贴广告。既占空间让人厌烦,又没人会搭理,于人于己都无利。

关于好例子网

本站旨在为广大IT学习爱好者提供一个非营利性互相学习交流分享平台。本站所有资源都可以被免费获取学习研究。本站资源来自网友分享,对搜索内容的合法性不具有预见性、识别性、控制性,仅供学习研究,请务必在下载后24小时内给予删除,不得用于其他任何用途,否则后果自负。基于互联网的特殊性,平台无法对用户传输的作品、信息、内容的权属或合法性、安全性、合规性、真实性、科学性、完整权、有效性等进行实质审查;无论平台是否已进行审查,用户均应自行承担因其传输的作品、信息、内容而可能或已经产生的侵权或权属纠纷等法律责任。本站所有资源不代表本站的观点或立场,基于网友分享,根据中国法律《信息网络传播权保护条例》第二十二与二十三条之规定,若资源存在侵权或相关问题请联系本站客服人员,点此联系我们。关于更多版权及免责申明参见 版权及免责申明

;
报警