Configuring NTP Client and NTP Server in Linux

NTP (Network Time Protocol)
Uses UDP connections and port 123.

Example installation in Ubuntu/Debian:

sudo apt-get install ntp

The current date can be viewed by the command:

date

Example of setting the time zone:

cp /usr/share/zoneinfo/Europe/Kiev /etc/localtime

Setting hours and minutes:

date -s 10:18
date --set 10:18

Example of full time setting (without spaces, in digital form):

date monthdayhourminuteyear.second

Checking the time server:

ntpdate -q SERVER

View status:

sudo ntpq -p
ntpq -c peers 

Let’s start editing the configuration file /etc/ntp.conf.

A few lines:
Specify the server with which to compare the time:

server 0.ubuntu.pool.ntp.org
server 1.ubuntu.pool.ntp.org
...

We prohibit all access to the server:

restrict default ignore

Or we allow access from the internal network:

restrict 192.168.0.0 mask 255.255.255.0 nomodify notrap

Restart ntp to make the changes in the configuration file take effect:

sudo service ntp restart

An example of time synchronization from the Windows command line with a Linux server:

net time \\SERVER /set /yes

See also:
IPTables rules for NTP and SNTP

IPTables rules for NTP and SNTP

To open access to the NTP client and NTP server in IPTables, you need to add rules:

sudo iptables -A OUTPUT -p udp -m udp -m multiport --dports 123 -m state --state NEW -j ACCEPT
sudo iptables -A INPUT -m state --state NEW -p udp --dport 123 -j ACCEPT

To access only a particular network, for example 10.0.0.0/24:

sudo iptables -A OUTPUT -p udp -m udp -m multiport --dports 123 -m state --state NEW -j ACCEPT
sudo iptables -A INPUT -s 10.0.0.0/24 -m state --state NEW -p udp --dport 123 -j ACCEPT

To remove a rule, we’ll specify the same command, replacing -A with -D, for example:

sudo iptables -D OUTPUT -p udp -m udp -m multiport --dports 123 -m state --state NEW -j ACCEPT
sudo iptables -D INPUT -m state --state NEW -p udp --dport 123 -j ACCEPT

To view the list of rules, use the command:

sudo iptables -nvL

See also:
Configuring IPTables
Configuring NTP Client and Server in Linux