Massimo
Massimo

Reputation: 3450

c# raw socket ip header total length

I am using udp raw sockets.

I wish to read only the first, for example, 64 bytes of every packet.

ipaddr = IPAddress.Parse( "10.1.2.3" );

sock = new Socket(AddressFamily.InterNetwork, SocketType.Raw, ProtocolType.IP);
sock.Bind(new IPEndPoint(ipaddr, 0));
sock.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.HeaderIncluded, true);
sock.IOControl(IOControlCode.ReceiveAll, BitConverter.GetBytes(RCVALL_IPLEVEL), null);
sock.ReceiveBufferSize = 32768;

byte[] buffer = new byte[64];   // max IP header, plus tcp/udp ports
while (!bTheEnd )
{
    int ret = sock.Receive(buffer, buffer.Length, SocketFlags.None);
    ...
}

I receive the packets, but all with IP header' "total length" <= 64.

If I use a bigger buffer ( byte[] buffer = new byte[32768] ), I got the right "total length" ( now its value is <= 32768 ).

The goal is to get all the packets, only the IP header, with their corret packet length; my routine doesn't have to cause packet fragmentation into the tcp/ip stack.

Upvotes: 0

Views: 2094

Answers (1)

Jacek Gorgoń
Jacek Gorgoń

Reputation: 3214

SocketFlags.Peek means the data returned will be left intact for a subsequent read - that's why you get same data after reading again. To read subsequent packets you don't want to use Peek, just perform a regular read with no special flags.

According to documentation:

If the datagram you receive is larger than the size of the buffer parameter, buffer gets filled with the first part of the message, the excess data is lost and a SocketException is thrown.

Is that the behavior you're after?

Upvotes: 1

Related Questions