Skip to content

Latest commit

 

History

History
96 lines (66 loc) · 3.09 KB

lab7.md

File metadata and controls

96 lines (66 loc) · 3.09 KB

7. Lab: Network time

Instructions

  1. Implement RFC 868.

Additional information

RFC (Released For Comments) 868 defines the Network Time Protocol (NTP), that works over UDP and TCP protocols.

NTP servers:

  • ntp1.arnes.si
  • ntp2.arnes.si

Detailed instructions

1. Task

Implement a simple program in any language that sends a query to the NTP server and can determine the time from the response.

An example of a program in the Python programming language:

import socket
import struct
import datetime

port = 37
host = "ntp1.arnes.si"

sock = socket.socket()
sock.connect((host, port))

# Read 4 bytes from a socket.
data = sock.recv(4)

# When we have numbers larger then 1 byte. Internet orders
# bytes in such a way that the first byte is most important
# -> BigEndian. Intel processors order bytes in such a way
# that the last byte is most important -> LittleEndian.
num = struct.unpack("!I", data)[0]

print(data, num)

# Starting time in unix is from 1.1.1970 in RFC is 1.1.1900.
# Difference in seconds is 2208988800.

networktime = datetime.datetime.fromtimestamp(num-2208988800)

print(networktime)

An example of a program in the Python programming language:

import java.io.DataInputStream;
import java.io.IOException;
import java.net.Socket;
import java.time.LocalDateTime;
import java.time.ZoneOffset;

public class NTP {

    public static void main(String args[])
    {
        try {
            Socket socket = new Socket("ntp1.arnes.si", 37);

            DataInputStream dis = new DataInputStream(socket.getInputStream());
            int i = dis.readInt();  // Unsigned integer!
            
            System.out.println(i);
            System.out.println(Integer.toBinaryString(i));
            System.out.println(Long.toBinaryString(i));
            
            // When cast into long the most important bit is
            // propagated into the first bytes of the long.
            // We multiply it with 0xffffffffL, which is 4
            // bytes of 1, so that the propagated 1 from the
            // long top 4 bytes are set back to 0.
            
            long time = (long)i & 0xffffffffL;
            System.out.println(Long.toBinaryString(0xffffffffL));
            System.out.println("Time:" + time);

            // NTP time starts from 1.1.1900
            // Epoch time starts from 1.1.1970

            long cas_epoch = time - 2208988800L;
            
            System.out.println("cas_epoch:" + cas_epoch);
            System.out.println("LocalTime:" + LocalDateTime.
            
            ofEpochSecond(cas_epoch, 0, ZoneOffset.of("+1")));

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}