Program.cs 8.8 KB

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