DEV Community

Discussion on: Build ur TCP/IP packet #1

Collapse
 
ac000 profile image
Andrew Clayton

Of course this can be simplified somewhat by using the header structures that are already defined, e.g struct tcphdr in netinet/tcp.h, there are also headers defined for UDP, IPv4, IPv6, ethernet etc...

Simplified example, also note the use of htons(3) to take care of endianess...

#include <netinet/tcp.h>
#include <arpa/inet.h>

int main(void)
{
        struct tcphdr tcphdr = { 0 };

        /* source port */
        tcphdr.th_sport = htons(80);

        /* destination port */
        tcphdr.th_dport = htons(3258);

        /* etc ... see struct tcphdr in /usr/include/netinet/tcp.h */

        return 0;
}

Hopefully you'll agree that's cleaner, more readable and maintainable code...

Cheers,
Andrew

Thread Thread
 
ctrivinoe profile image
Trivi

Totally agree, my code was originally part of a university work and I thought to extend it to a didactic project to better understand the structure of the packages (at a lower level). I will continue to publish on the subject, so I would like you to review it when I do (you have much more knowledge than me (without doubts) on the subject, so I'm sure I learn from you 😋).

Thx for reading and aport!