How can i access and modify my UDP header? - c++

I am just starting out with network programming and I am having trouble keeping up with some of the stuff. Namely because there is a lot of auto-magic stuff going on under the hood that is hidden away from me, and I cant get my head around it all. In my current app, I take user input like so:
char buff[1024];
cout << "Enter a message:";
fgets(buff, 1024, stdin);
And i can easily send that off by essentially doing this:
sendto(m_socket, buff, size, flags, (SOCKADDR*)&addr, sizeof(addr));
The other variables (size,flags,etc) are obviously initialized and configured somewhere between the input and sendto call.
This all works fine, and the other end receives the data fine. the server does
recvfrom(m_socket, (char*)data, max, flags, (SOCKADDR*)&fromAddr, &fromLength)
and I can then just print out 'data' into the console, and it'd be my message.
So where exactly is my UDP packets header? Did i have to specify it? when i pass in some data, is the 'data' part of a standard UDP packet filled with the data i specify, and the header automatically populated for me (source IP, destination IP)? If so how do i even access it?
A lot of websites I have looked at talk about headers and what not. It seems to be this very specific thing. But I dont understand how this illusive header works.. I'd like to define my own header with things like segment number, total segments, etc. but i dont know how to go about this at all. My googleing isnt sending me in the right direction either..!

The UDP headers are not available to the application when you use the standard interfaces from the operating system (socket() with SOCK_DGRAM, sendto(), recvfrom() and such). They are automatically handled by the operating system's network stack. They are automatically added when you send the message and automatically stripped when you receive.
Depending on the operating system, there are some means you can write and manage the UDP headers directly over the IP routing layer, but that is certainly unusual, and would probably require administrative privileges.
If you want to define your own headers for your own purposes, you must do so inside the body of the message, i.e. parse and interpret what you send and receive sendto() and recvfrom(), thus creating what is called an application protocol. Networking is a layered architecture, where applications sits upon UDP or TCP, that sits upon IP that (usually) sits upon Ethernet or Wi-Fi. Each one has its own headers that is stripped when the data is handled to the above layer, and you only gets what you send on the application layer (maybe you can miss some packets or get them out of order, because UDP doesn't give you those guarantees, as TCP does).

UDP does not contain such things as headers, segment numbers and total segments. In fact, a UDP datagram contains nothing except the buffer that you sendto.
You can add extra information by including them with your message. Instead of simply putting your message in your buffer, make a larger buffer into which you put whatever "header" information you would like and then put your message afterwards.
From UDP's perspective, all it sees is data. It is up to the program on the receiving end to parse this data and realize that a certain part it is metadata and the other part of it is regular data.
You will have to define your message format such that it is easy for the receiving program to extract the "header" portion of the buffer. There are two common schemes: fixed headers and variable length headers.
If you are going for a fixed header, you assume that the first X bytes of every UDP message are metadata. You pick the X and it never changes per message. The recipient then knows to read X bytes as the header and all the rest as a message.
If you are going for a variable length header, you need to be able to tell the receiving end how long the header is for each particular message. A common scheme is that the first 4 bytes of the header contain an integer which says how long the header part of the message is. Then the receiving end reads that many bytes and interprets that as the header. Then it reads the rest of the data and interprets that as the message.
Lastly, the source IP and the destination IP are not properties of your UDP messages but rather properties of your socket. You can retrieve this information by inspecting the socket itself.

You can receive the UDP headers based the sockets you open up. You can receive the complete packet using socket(AF_PACKET,SOCK_RAW,htons(ETH_P_ALL));
If this socket is enabled for recvfrom then you receive the complete packet including your headers.

Related

What the receiver do if the message is segmented by TCP

I raised this question when reading the source code of muduo (C++ network library).
If a client sends a big size message which will be segmented by TCP, what happens in server side? (Does server know this message is already segmented?)
And is it necessary for network library to wait for the whole message and do not interrupt the upper layer?
When dealing with a stream protocol like TCP, you already have to reassemble received data into chunks of your own choosing. That's either a fixed number of bytes per chunk, or it's decided dynamically by parsing the data in terms of your application's protocol (e.g. HTTP).
You don't know when you receive a packet from the network layer that it has been segmented: you only know that you received some data. You may know (because you understand your own protocol) that you're expecting more data to finish the chunk, but you won't know whether there is any more data until you receive it. If you do receive it.
Conversely, a single TCP packet may well contain more than a single chunk of your application-layer data! Again, you need to be aware that there is no direct relationship between the two things.
You can, however, depend on the TCP packets being delivered in the same order in which they were sent, which is nice.
Simple analogy: a big ol' ship, carrying cargo. It may be carrying 40 cars, or it may be carrying just half the quantity of parts required to construct an airplane. Or it may be carrying both! You don't know until you read the shipping manifest and consult your own records on delivery. It's then your responsibility to unpack what you've received and do what you need to do with it.
And is it necessary for network library to wait for the whole message and do not interrupt the upper layer?
If the library wants to pass a full "message" to the upper layer, then usually yes. Some approaches will just block waiting for a full message, but that's not common nowadays. Asynchronous I/O is your friend.
(This was a generic answer, written with no knowledge of what muduo does specifically.)

reassembly of tcp packet

I'm parsing a file with lots of tcp packets which i need to parse. The problem is that they get segmented and i can't find any indication when and where they do so. No flags or anything else indicates, that the middle of current packet may contain the beginning of the next one. The protocol above tcp is FIX(used in online trading) but i'd like for my code to be able to work with any protocols(or at least understand which is protocol is it).
I'm writing code in C++ and can't use any additional libraries.
So, how do i figure out what is the protocol above tcp and where it gets segmented ?
You can't. TCP/IP is conceptually a stream, not a sequence of messages (the fact that it is ultimately implemented as a sequence of packets is irrelevant). When you write a sequence of bytes to a TCP/IP stream, that sequence is added to the stream; it is not treated as a message which should maintain its own identity. No notion of message begin/end is transmitted along with the stream, unless you do so yourself in your own protocol.
If you find this hard to believe, consider how it works for files: if you write a sequence of bytes to a file, that sequence does not somehow become a record that you can later identify and retrieve. If you want that kind of structure you have to add it yourself. The same is true for TCP/IP.
The transport packets used to implement TCP/IP have no relation to the data blocks you specify with your API calls; they are merely a way to implement the TCP/IP stream. For some use cases there may appear to be a mapping, but this is accidental.
The only way to split a TCP/IP stream back into separate messages is by using knowledge of the protocol running on top of TCP/IP. In your case this is FIX. I assume you know how that works; you can use that knowledge to correctly split the FIX data back into its original messages. A generic TCP/IP message splitter cannot be made.
As I can see your problem is to separate TCP packets. To solve it you can relay on length of payload (this answer) and checksum. If checksum is correct for data with specified length, than your packet is correct, if no - you need seek in thee previous part for start of the packet or drop this part of data. At least this approach will help you to find point where dada was segmented.
For more precise answer it will be better to see little part of data.
But main your problem is segmentation of packets. For better performance you should try to exclude this problem (maybe change network card to Intel).

Are TCP packets reordered usually?

I am reimplementing an old network layer library, but using boost asio this time. Our software is tcpip dialoging with a 3rd party software. Several messages behave very well on both sides, but there is one case I misunderstand:
The 3rd party sends two messages (msg A and B) one after the other (real short timing) but I receive only a part of message A in tcp-packet 1, and the end of message A and the whole message B in tcp-packet 2. (I sniff with wireshark).
I had not thought of this case, I am wondering if it is common with tcp, and if my layer should be adaptative to that case - or should I say to the 3rd party to check what they do on their side so as I received both message in different packets.
Packets can be fragmented and arrive out-of-sequence. The TCP stack which receives them should buffer and reorder them, before presenting the data as an incoming stream to the application layer.
My problem is with message B, that I don't see because it's after the end of message one in the same packet.
You can't rely on "messages" having a one-to-one mapping to "packets": to the application, TCP (not UDP) looks like a "streaming" protocol.
An application which sends via TCP needs another way to separate messages. Sometimes that's done by marking the end of each message. For example SMTP marks the end-of-message as follows:
The transmission of the body of the mail message is initiated with a
DATA command after which it is transmitted verbatim line by line and
is terminated with an end-of-data sequence. This sequence consists of
a new-line (), a single full stop (period), followed by
another new-line. Since a message body can contain a line with just a
period as part of the text, the client sends two periods every time a
line starts with a period; correspondingly, the server replaces every
sequence of two periods at the beginning of a line with a single one.
Such escaping method is called dot-stuffing.
Alternatively, the protocol might specify a prefix at the start of each message, which will indicate the message-length in bytes.
If you're are coding the TCP stack, then you'll have access to the TCP message header: the "Data offset" field tells you how long each message is.
Yes, this is common. TCP/IP is a streaming protocol and your "logical" packet may be split across many "physical" packets, so the client is responsible for assembling the higher-level packets. Additionally, TCP/IP guarantees the proper ordering, so you don't have to worry about assembling out of order packets.
your problem has got nothing to do with TCP at all. your problem is that you expected asio to do the message parsing for you. it does not, you have to implement it.
if your messages are all the same size do an async read for that size.
if they are of different length do a async read for your header size, analyze the header and do an async read for the rest of the message according to the header.
if your messages are of variable length and the size is unknown but there is a defined end character or sequence then you have to save the remaining bytes behind that end sequence and append the next read to that remainder.

Receiving all data sent with C sockets

If I write a server, how can I implement the receive function to get all the data sent by a specific client if I don't know how that client sends the data?
I am using a TCP/IP protocol.
If you really have no protocol defined, then all you can do is accept groups of bytes from the client as they arrive. Without a defined protocol, there is no way to know that you have received "all the bytes" that the client sent, since there is always the possibility that a network failure occurred somewhere between the client and your server during transmission, causing the last part of the stream not to arrive at the server. In that case, you would get the usual end-of-stream indication from the TCP socket (e.g. recv() returning 0, or EWOULDBLOCK if you are using non-blocking sockets), so you would know that you aren't going to receive any more data from the client (because the TCP connection is now disconnected)... but that isn't quite the same thing as knowing you have received all of the data the client meant for you receive.
Depending on your application, that might be good enough. If not, then you'll have to work out a protocol, and trust that your clients will abide by the rules of that protocol. Having the client send a header first saying how many bytes it plans to send is a good approach; or having it send some special "Okay, that's all I meant to send" indicator is also possible (although if you do it that way, you have to watch out for false positives if the special indicator could appear by chance inside the data itself)
One call to send does not equal one call to recv. Either send a header so the receiver know how much data to expect, or send some sort of sentinel value so the the receiver knows when to stop reading.
It depends on how you want to design your protocol.
ASCII protocols usually use a special character to delimit the end of the data, while binary protocols usually send the length of the data first as a fixed-size integer (both sides know this size) and then the variable-length data follows.
You can combine size with your data in one buffer and call send once. People usually use first 2 bytes for size of data in a packet. Like this,
|size N (2 bytes) | data (N bytes) |
In this case, you can contain 65535 byte-long custom data.
Since TCP does not preserve message boundary, it doesn't matter how many times you call send. You have to call receive until you get N size(2 bytes) then you can keep calling receive until you have N bytes data you sent.
UPDATE: This is just a sample to show how to check message boundary in TCP. Security/Encryption is a whole different story and it deserves a new thread. That said, do not simply copy this design. :)
TCP is stream-based, so there is no concept of a "complete message": it's given by a higher-level protocol (e.g. HTTP) or you'd have to invent it yourself. If you were free to use UDP (datagram-based), then there would be no need to do send() multiple times, or receive().
A newer SCTP protocol also supports the concept of a message natively.
With TCP, to implement messages, you have to tell the receiver the size of the message. It can be the first few bytes (commonly 2, since that allows messages up to 64K -- but you have to be careful of byte order if you may be communicating between different systems), or it can be something more complicated. HTTP, for example, has a whole set of rules by which the receiver determines the length of the message. One of them is the Content-Length HTTP header, which contains a string representing the number of bytes in the body of the message. Header-only HTTP messages are simply delimited by a blank line. As you can see, there are no easy (or standard) answers.
TCP is a stream based protocol. As such there is no concept of length of data built into TCP in the same way as there is no concept of data length for keyboard input.
It is therefore up to the higher level protocol to specify the end of the message. This can be done by including the packet length in the protocol or specifying a special end-of-message byte sequence.
For example HTTP headers are terminated by a double \r\n sequence and the length of the message body can be obtains from the Content-Length header.

Count the number of packets sent to a server from a client?

So I'm almost done an assignment involving Win32 programming and sockets, but I have to generate and analyze some statistics about the transfers. The only part I'm having trouble with is how to figure out the number of packets that were sent to the server from the client.
The data sent can be variable-length, so I can't just divide the total bytes received by a #define'd value.
We have to use asynchronous calls to do everything, so I've been trying to increment a counter with every FD_READ message I get for the server's socket. However, because I have to be able to accept a potentially large file size, I have to call recv/recvfrom with a buffer size around 64k. If I send a small packet (a-z), there are no problems. But if I send a string of 1024 characters 10x, the server reports 2 or 3 packets received, but 0% data loss in terms of bytes sent/received.
Any idea how to get the number of packets?
Thanks in advance :)
This really boils down to what you mean by 'packet.'
As you are probably aware, when a TCP/UDP message is sent on the wire, the data being sent is 'wrapped,' or prepended, with a corresponding TCP/UDP header. This is then 'wrapped' in an IP header, which is in turn 'wrapped' in an Ethernet frame. You can see this breakout if you use a sniffing package like Wireshark.
The point is this. When I hear the term 'packet,' I think of data at the IP level. IP data is truly packetized on the wire, so packet counts make sense when talking about IP. However, if you're using regular sockets to send and receive your data, the IP headers, as well as the TCP/UDP headers, are stripped off, i.e., you don't get this information from the socket. And without that information, it is impossible to determine the number of 'packets' (again, I'm thinking IP) that were transmitted.
You could do what others are suggesting by adding your own header with a length and a counter. This information will help you accurately size your receive buffers, but it won't help you determine the number of packets (again, IP...), especially if you're doing TCP.
If you want to accurately determine the number of packets using Winsock sockets, I would suggest creating a 'raw' socket as suggested here. This socket will collect all IP traffic seen by your local NIC. Use the IP and TCP/UDP headers to filter the data based on your client and server sockets, i.e., IP addresses and port numbers. This will give an accurate picture of how many IP packets were actually used to transmit your data.
Not a direct answer to your question but rather a suggestion for a different solution.
What if you send a length-descriptor in front of the data you want to transfer? That way you can already allocate the correct buffer size (not too much, not too little) on the client and also check if there were any losses when the transfer is over.
With TCP you should have no problem at all because the protocol itself handles the error-free transmission or otherwise you should get a meaningful error.
Maybe with UDP you could also split up your transfer into fixed-size chunks with a propper sequence-id. You'd have to accumulate all incoming packages before you sort them (UDP makes no guarantee on the receive-order) and paste the data together.
On the other hand you should think about it if it is really necessary to support UDP as there is quite some manual overhead if you want to get that protocol error-safe... (see the Wikipedia Article on TCP for a list of the problems to get around)
Do your packets have a fixed header, or are you allowed to define your own. If you can define your own, include a packet counter in the header, along with the length. You'll have to keep a running total that accounts for rollover in your counter, but this will ensure you're counting packets sent, rather than packets received. For an simple assignment, you probably won't be encountering loss (with UDP, obviously) but if you were, a packet counter would make sure your statistics reflected the sent message accurately.