开发者

How to send raw data over a network? [duplicate]

This question already has answers here: How to fake source ip-address of a udp-packet? (4 answers) Closed 3 years ago.

I have some data stored in a byte-array. The data contains an IPv4 packet (which contains a UDP packet).

I want to send this array raw over the network using C# (preferred) or C++. I don't want to use C#'s udp-client for开发者_JAVA技巧 example.

Does anyone know how to perform this?


Try raw sockets (specify SOCK_RAW for the socket type).
You will be responsible for calculating the IP checksums as well. This can be a little annoying.


using System.Net;
using System.Net.Sockets;

public class Test
{
    public void Send(byte[] rawData, IPEndPoint target)
    {
        // change what you pass to this constructor to your needs
        Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IPv4);

        try
        {
            s.Connect(target);
            s.Send(rawData);
        }
        catch(Exception ex)
        {
            // handle this exception
        }
    }
}


Here is a way to send raw data over NIC http://www.codeproject.com/KB/IP/sendrawpacket.aspx As mentioned above Windows is restricting raw socket operations, you have to modify NDIS driver to be able to send whatever you want. Of course you will then have a problem with digital driver signing on Vista/7 (can be temporary bypassed with test mode).


When you have raw data (ie a byte-array) and you want to send it over a network, then you need some sort of encoding:

  1. If you send multiple blocks (whole arrays), the recipient needs to be able to differentiate between the end of one and the start of the next.
  2. If the data is really large its is better to split it into smaller blocks (yes, packets) to play well with other users of the network.
  3. You need to know that the data is error-free at the client as networks have the tendency to be unreliable at exactly the wrong time for you.

Encoding solves the first point above.
TCP is the conventional solution to the second two points.

Examples of encoding are:

  • HTTP encodes the length in cr delimited lines, then a pure binary blob.
  • Text Files could be ctrl-z delimited.
  • XML can be delimited simply by its syntax of tags.
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜