Program.cs 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233
  1. //////////////////////////////////
  2. // C# 也可以做Sniffer
  3. // SharpSniffer
  4. ////////////////////////////////
  5. using System;
  6. using System.Collections.Generic;
  7. //using System.Linq;
  8. using System.Text;
  9. using System.Net;
  10. using System.Net.Sockets;
  11. namespace SharpSniffer
  12. {
  13. class Program
  14. {
  15. static long AllCount = 0;
  16. static void Main(string[] args)
  17. {
  18. try
  19. {
  20. //创建socket
  21. Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Raw, ProtocolType.IP);
  22. using (socket)
  23. {
  24. PrintLine("socket created!");
  25. //绑定到本机,端口可以任意
  26. var localHostIpAddress = GetHostAdress();
  27. Console.WriteLine("trying to bind to local IP: {0}", localHostIpAddress);
  28. socket.Bind(new IPEndPoint(localHostIpAddress, 0));
  29. PrintLine("binded to [" + socket.LocalEndPoint + "]");
  30. byte[] outValue = BitConverter.GetBytes(0);
  31. byte[] inValue = BitConverter.GetBytes(1);
  32. socket.IOControl(IOControlCode.ReceiveAll, inValue, outValue); //对IO设置为可以接受所有包
  33. PrintLine("IOControl seted!");
  34. byte[] buf = new byte[65535]; //缓存大一点没关系,小了可能一次放不下
  35. PrintLine("Sniffer begined.");
  36. IPEndPoint ipep = new IPEndPoint(IPAddress.Any, 0); //从任何地方接收数据
  37. int index = 0; //表示当前是第几个包(1based)
  38. while (true)
  39. {
  40. index++;
  41. try
  42. {
  43. ipep.Address = IPAddress.Any; //从任何地方接收数据
  44. ipep.Port = 0;
  45. EndPoint ep = ipep;
  46. int recvedSize = socket.ReceiveFrom(buf, ref ep); //用ReceiveFrom接受数据
  47. // socket.Receive(buf); //用Receive也能接受到数据,不过使用ReceiveFrom可以直接获取发送方IP地址
  48. AllCount += recvedSize;
  49. //接收到包了,打印出来
  50. //Print('[');
  51. //Print(GetCurrentTimeString());
  52. //PrintLine("] Received [" + recvedSize + "] bytes from [" + ep.ToString() + "]");
  53. ////string s = Encoding.ASCII.GetString(buf, 0, recvedSize);
  54. ////Print("ASCII: \n");
  55. ////PrintLine(s);
  56. //string s = GetByteArrayHexString(buf, 0, recvedSize);
  57. //Print("Hex: \n");
  58. //PrintLine(s);
  59. Print(index);
  60. PrintLine(string.Format(" This: {1:f2} KB / AllCount: {1:f2} MB",
  61. (double)recvedSize / 1024, (double)AllCount / 1024 / 1024));
  62. if (recvedSize > 1000)
  63. {
  64. PrintLine("////////////////////");
  65. }
  66. }
  67. catch (Exception ex)
  68. {
  69. if (ex is SocketException)
  70. {
  71. var sex = (SocketException)ex;
  72. Console.Error.WriteLine("SocketErrorCode=" + sex.ErrorCode);
  73. }
  74. Console.Error.WriteLine(ex);
  75. }
  76. }
  77. }
  78. }
  79. catch (Exception ex)
  80. {
  81. if (ex is SocketException)
  82. {
  83. var sex = (SocketException)ex;
  84. Console.Error.WriteLine("SocketErrorCode=" + sex.ErrorCode);
  85. }
  86. Console.Error.WriteLine(ex);
  87. }
  88. }
  89. //获取本机IP地址
  90. private static IPAddress GetHostAdress()
  91. {
  92. string hostName = Dns.GetHostName();
  93. var hostAddreses = Dns.GetHostAddresses(hostName);
  94. List<IPAddress> addressList = new List<IPAddress>(hostAddreses.Length);
  95. foreach (var item in hostAddreses)
  96. {
  97. if (item.AddressFamily == AddressFamily.InterNetwork)
  98. {
  99. addressList.Add(item);
  100. }
  101. }
  102. if (addressList.Count != 0)
  103. {
  104. if (addressList.Count == 1)
  105. {
  106. return addressList[0];
  107. }
  108. else
  109. {
  110. Console.WriteLine("请选择要绑定到的本机IP地址(IPv4):");
  111. for (int i = 0; i < addressList.Count; i++)
  112. {
  113. var addr = addressList[i];
  114. Console.WriteLine("\t{0}: {1}", i, addr);
  115. }
  116. int sel = int.Parse(Console.ReadLine());
  117. return addressList[sel];
  118. }
  119. }
  120. else
  121. {
  122. Console.Write("请输入本机IP地址:");
  123. string s = Console.ReadLine();
  124. return IPAddress.Parse(s);
  125. }
  126. }
  127. //获取表示当前时间的字符串
  128. private static string GetCurrentTimeString()
  129. {
  130. DateTime now = DateTime.Now;
  131. return now.Hour + ":" + now.Minute + ":" + now.Second + "." + now.Millisecond;
  132. }
  133. const string HexValues = "0123456789ABCDEF";
  134. //把字节数组转换为十六进制表示的字符串
  135. private static string GetByteArrayHexString(byte[] buf, int startIndex, int size)
  136. {
  137. StringBuilder sb = new StringBuilder(size * 5);
  138. sb.AppendFormat("{0,3:X}: ", 0);
  139. int j = 1;
  140. for (int i = startIndex, n = startIndex + size; i < n; i++, j++)
  141. {
  142. byte b = buf[i];
  143. char c = HexValues[(b & 0x0f0) >> 4];
  144. sb.Append(c);
  145. c = HexValues[(b & 0x0f)];
  146. sb.Append(c);
  147. sb.Append(' ');
  148. if ((j & 0x0f) == 0)
  149. {
  150. sb.Append(' ');
  151. //sb.Append(Encoding.ASCII.GetString(buf,i-15,8));
  152. AppendPrintableBytes(sb, buf, i - 15, 8);
  153. sb.Append(' ');
  154. //sb.Append(Encoding.ASCII.GetString(buf, i - 7, 8));
  155. AppendPrintableBytes(sb, buf, i - 7, 8);
  156. if (i + 1 != n)
  157. {
  158. sb.Append('\n');
  159. sb.AppendFormat("{0,3:X}: ", i - 1); //偏移
  160. }
  161. }
  162. else if ((j & 0x07) == 0)
  163. {
  164. sb.Append(' ');
  165. }
  166. }
  167. int t;
  168. if ((t = ((j - 1) & 0x0f)) != 0)
  169. {
  170. for (int k = 0, kn = 16 - t; k < kn; k++)
  171. {
  172. sb.Append(" ");
  173. }
  174. if (t <= 8)
  175. {
  176. sb.Append(' ');
  177. }
  178. sb.Append(' ');
  179. // sb.Append(Encoding.ASCII.GetString(buf, startIndex + size - t, t>8?8:t));
  180. AppendPrintableBytes(sb, buf, startIndex + size - t, t > 8 ? 8 : t);
  181. if (t > 8)
  182. {
  183. sb.Append(' ');
  184. // sb.Append(Encoding.ASCII.GetString(buf, startIndex + size - t + 8, t - 8));
  185. AppendPrintableBytes(sb, buf, startIndex + size - t + 8, t - 8);
  186. }
  187. }
  188. return sb.ToString();
  189. }
  190. //向sb中添加buf中可打印字符,不可打印字符用'.'代替
  191. private static void AppendPrintableBytes(StringBuilder sb, byte[] buf, int startIndex, int len)
  192. {
  193. for (int i = startIndex, n = startIndex + len; i < n; i++)
  194. {
  195. char c = (char)buf[i];
  196. if (!char.IsControl(c))
  197. {
  198. sb.Append(c);
  199. }
  200. else
  201. {
  202. sb.Append('.');
  203. }
  204. }
  205. }
  206. //打印t+'\n'
  207. static void PrintLine<T>(T t)
  208. {
  209. Console.WriteLine(t);
  210. }
  211. //打印t
  212. static void Print<T>(T t)
  213. {
  214. Console.Write(t);
  215. }
  216. }
  217. }