How send raw ethernet packet with C#?

2019-01-06 13:26发布

问题:

Is there a way to send raw packet Ethernet to other host via C#? In Windows 7 if it makes difference.

回答1:

Based on suggestion by Saint_pl:

I found probably better solution - similar to SharpPcap. It's Pcap.Net - .NET wrapper for WinPcap. Now I can modify my packets whatever I want.


I have some resources for you that maybe helpful. I don't try that solutions in Windows 7 but maybe it contains some good info to start.

Raw Ethernet Packet Manipulation or mirror on CodeProject

This purpose of this article is to explain how to send a raw Ethernet packet using C# on a Microsoft platform. A raw Ethernet packet is the complete Layer 2 network frame that is sent to the physical wire. Sending a frame like this allows you to manipulate the target and source MAC addresses and the Layer 3 protocol fields.

Also some info on raw sockets (just in case you interesting too):

Client (and Server) Sockets Communication take a look on whole chapter but here key parts:

  • C# Raw UDP Socket Program Example
  • C# Raw Socket Ping Program Example part A | part B
  • All examples

Not sending packets but maybe interesting: A Network Sniffer in C#, SharpPcap - A Packet Capture Framework for .NET



回答2:

iphelper API has some low level stuff - but probably not quite as low as you want to get



回答3:

Socket server = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
IPEndPoint ip = new IPEndPoint(IPAddress.Parse("10.25.184.11"), 4456);

server.Connect(ip);

byte[] sendData = new byte[] { 0, 8, 32, 64 };
server.Send(sendData);

//done. now let's listen for data

byte[] receiveData = new byte[1024];
int receivedDataLength = server.Receive(receiveData);

//if the response is a string message
string stringData = Encoding.ASCII.GetString(receiveData, 0, receivedDataLength);
Console.WriteLine(stringData);