How to create network packets using C / C ++

I want to create a network packet to send (for example) port 123 to an NTP server so that I can receive and parse the returned packet. The goal is to better understand how packets are generated, read, and answered by network systems.

(1) Should you use a structure to create a package?

(2) I am not sure how to correctly fill in the various fields within the structure; for example, if source and destination IP addresses must be set with hexadecimal values? Or is there a more human-friendly way?

(3) Then, as soon as the fields are filled out, is it possible to send the structure via send () / write () via a UDP connection to an NTP server? (or TCP if the protocol requires it)

Is my approach reasonable? I read NTP RFC, but I'm still not sure what my client should send to the server (for example, IP address, should I care about this with a network layer header?) I modeled this NTP struct after the โ€œtransferโ€ example in the Appendix A RFC 5905. We apologize if my question is poorly worded or too long. Thanks in advance for any help. The following is a sample code in the RFC 5905 sample code.

typedef unsigned long ipaddr; //32 bits (4 bytes) typedef signed char s_char; //character type as number, -128..127 typedef unsigned int tdist; //character type as number, 0..255 typedef unsigned long long tstamp; //64 bits (8 bytes) typedef unsigned long digest; //32 bits (4 bytes) struct Ntp { ipaddr dstaddr; ipaddr srcaddr; char version; char leap; char mode; char stratum; char poll; s_char precision; tdist rootdelay; tdist rootdisp; char refid; tstamp reftime; tstamp org; tstamp rec; tstamp xmt; int keyid; digest dgst; } Ntp; int main() { struct Ntp packet; //packet.dstaddr=WHAT_GOES_HERE; //... //... //packet.dgst=WHAT_GOES_HERE; return 0; } 
+6
source share
1 answer

You don't seem to have much experience writing network protocols. Declaring a structure and writing it is not an option. I also point you to http://fixunix.com/ntp/257876-any-samples-ntp-sntp-client-code.html and, in particular, call the following points:

  • Why do you want to minimize your own compared to running one of the existing packages?

  • One of the problems when writing an NTP client is the correct time.

  • The other does not clog the rest of the network or does not create an unreasonable load on the servers.

In any case, as discussed in the thread I pointed out to you, you want to use SNTP and should take a look at the SNTP link implementation in the ntp tar file to indicate the path and help you understand what you should do.

+2
source

Source: https://habr.com/ru/post/891327/


All Articles