DEV Community

Discussion on: Build ur TCP/IP packet #1

Collapse
 
ctrivinoe profile image
Trivi

Exactly! There are several ways to do this step, finally I used this way to use both, bit shift and logic gate operation.
According to the example, for the port 80 (bits in green are the insert):

packet[0] = sourcePort >> 8;


packet[1] = sourcePort & 0xFF;

and, for the sourcePort 3258:
packet[2] = destinationPort >> 8;

packet[3] = destinationPort & 0xFF;

I hope I have clarified the insertion more, although you had deduced it well!

Thx for reading and commenting!

Collapse
 
abdisalan_js profile image
Abdisalan

Thanks for the deeper explanation!

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!