@xunuo
2017-08-11T10:37:59.000000Z
字数 2527
阅读 1455
网络数据包分析
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using SharpPcap;
using SharpPcap.LibPcap;
using PacketDotNet;
using TwzyProtocol;
namespace practice1
{
class Program
{
//static int vis = 0;
static string stringdata;
static void Main(string[] args)
{
//获取网络设备
var device = CaptureDeviceList.Instance;
if (device.Count < 1)
{
Console.WriteLine("暂无可用网络设备!\n");
return;
}
int i = 0;
foreach (ICaptureDevice cap in device)
{
Console.WriteLine("{0},{1},{2}", i, cap.Name, cap.Description);//打印所有可用网络设备;
i++;
}
//选择为要用的设备:
Console.WriteLine("请选择要使用的网络设备:");
int j = int.Parse(Console.ReadLine());
if (j > i || j < 0)
{
Console.WriteLine("该设备不存在!\n");
return;
}
ICaptureDevice dev = device[j];
//string filter = "ip and tcp";
dev.OnPacketArrival += new PacketArrivalEventHandler(dev_OnPacketArrival);
dev.Open(DeviceMode.Normal, 1000);
dev.Filter = "port 80";
dev.StartCapture();
}
public static string ToHexString(byte[] bytes) // byte[]转16进制string
{
string hexString = string.Empty;
if (bytes != null)
{
StringBuilder strB = new StringBuilder();
for (int i = 0; i < bytes.Length; i++)
{
strB.Append(bytes[i].ToString("X2"));
}
hexString = strB.ToString();
}
return hexString;
}
static void dev_OnPacketArrival(object sender, CaptureEventArgs e)
{
// packetdata = e.Packet.Data;
stringdata = ToHexString(e.Packet.Data);
// Console.WriteLine(ToHexString(packetdata));
if (e.Packet.LinkLayerType == LinkLayers.Ethernet)
{
var packet = PacketDotNet.Packet.ParsePacket(e.Packet.LinkLayerType, e.Packet.Data);
Ethernet(packet);
}
}
static private void Ethernet(Packet packet)
{
var Ethernetpacket = PacketDotNet.EthernetPacket.GetEncapsulated(packet);
if (Ethernetpacket.Type == EthernetPacketType.IpV4 || Ethernetpacket.Type == EthernetPacketType.IpV6)
{
IpPacket ip = IpPacket.GetEncapsulated(packet);
if(ip.Protocol==IPProtocolType.TCP)
{
TcpPacket tcp = TcpPacket.GetEncapsulated(packet);
if(tcp.SourcePort==80||tcp.DestinationPort==80)
{
if (tcp.PayloadData.Length == 0)
return;
HttpPacket http = new HttpPacket(tcp.PayloadData);
Class1.Http(http);
}
}
}
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using SharpPcap;
using SharpPcap.LibPcap;
using PacketDotNet;
using TwzyProtocol;
namespace practice1
{
class Class1
{
static char[] ReplaceCharArry =
{
'\0','\a','\b','\f','\t','\v','?'
};//将字符表示为UTF-16代码单位;
static public void Http(HttpPacket http)
{
Console.WriteLine("Data Length:" + http.DataLength);
List<CommandTypeHead> httplist = http.CreatHeadList();
if (httplist.Count == 0)
return;
foreach (var i in httplist)
{
string ilist = i.Content;
foreach (var j in ReplaceCharArry)
{
ilist = ilist.Replace(j, '.');
}
Console.WriteLine(ilist);
}
}
}
}