This isn't possible using the TCP stack of the host simply because a TCP stack that follows RFC 793 isn't supposed to offer this kind of access to an application.
That is, there isn't (and there shouldn't be) a way to influence what the lower layers do with your data. Of course, there are ways to influence what TCP
does (Nagle for example) but that is against the spirit of the protocol. TCP
should be used for what it's best at: transferring a continuous, ordered stream of bytes. Nothing more, nothing less. No messages, packets, frames.
If after all you do need to control such details, you need to look at lower-level APIs. You could use SOCK_RAW
and PF_PACKET
.
Packet sockets are used to receive or
send raw packets at the device driver
(OSI Layer 2) level.
@gby mentioned UDP and that is (partially) a good idea: UDP
has a fixed size. But keep in mind that you will have to deal with IP fragmentation (or use IP_DONTFRAG
).