User Tools

Site Tools


ntpquery

[Start] [Cat] [About] [Syntax] [Scraps]


ntpQuery

Simple C program for checking an NTP server. The nmap script is too slow.

Build with

gcc -o ntpQuery ntpQuery.c

Run with

./ntpQuery 172.16.0.2
ntpQuery.gcc
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
#include <arpa/inet.h>
#include <time.h>
 
#define NTP_PORT 123
#define NTP_PACKET_SIZE 48
#define NTP_TIMESTAMP_DELTA 2208988800UL
 
typedef struct {
    uint8_t li_vn_mode;
    uint8_t stratum;
    uint8_t poll;
    uint8_t precision;
    uint32_t root_delay;
    uint32_t root_dispersion;
    uint32_t ref_id;
    uint32_t ref_ts_secs;
    uint32_t ref_ts_frac;
    uint32_t orig_ts_secs;
    uint32_t orig_ts_frac;
    uint32_t recv_ts_secs;
    uint32_t recv_ts_frac;
    uint32_t trans_ts_secs;
    uint32_t trans_ts_frac;
} ntp_packet;
 
int main(int argc, char *argv[]) {
    if (argc != 2) {
        fprintf(stderr, "Usage: %s <ntp_server>\n", argv[0]);
        exit(1);
    }
 
    int sockfd;
    struct hostent *server;
    struct sockaddr_in serv_addr;
    ntp_packet packet = { 0 };
 
    packet.li_vn_mode = 0x1b; // LI = 0, VN = 3, Mode = 3 (client)
 
    sockfd = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
    if (sockfd < 0) {
        perror("Error opening socket");
        exit(1);
    }
 
    server = gethostbyname(argv[1]);
    if (server == NULL) {
        fprintf(stderr, "Error resolving hostname\n");
        exit(1);
    }
 
    memset(&serv_addr, 0, sizeof(serv_addr));
    serv_addr.sin_family = AF_INET;
    memcpy(&serv_addr.sin_addr.s_addr, server->h_addr, server->h_length);
    serv_addr.sin_port = htons(NTP_PORT);
 
    if (sendto(sockfd, &packet, sizeof(ntp_packet), 0,
               (struct sockaddr *)&serv_addr, sizeof(serv_addr)) < 0) {
        perror("Error sending packet");
        exit(1);
    }
 
    struct timeval timeout = {1, 0}; // 1 second timeout
    setsockopt(sockfd, SOL_SOCKET, SO_RCVTIMEO, &timeout, sizeof(timeout));
 
    socklen_t addr_len = sizeof(serv_addr);
    if (recvfrom(sockfd, &packet, sizeof(ntp_packet), 0,
                 (struct sockaddr *)&serv_addr, &addr_len) < 0) {
        perror("Error receiving packet");
        exit(1);
    }
 
    packet.ref_id = ntohl(packet.ref_id);
    packet.ref_ts_secs = ntohl(packet.ref_ts_secs);
 
    time_t time = packet.ref_ts_secs - NTP_TIMESTAMP_DELTA;
    char refid[5] = {0};
    memcpy(refid, &packet.ref_id, 4);
 
    printf("Reference ID: %08X ", packet.ref_id);
    for(int i = 3; i >= 0; i--) {
        if(refid[i] >= 32 && refid[i] <= 126) {
            printf("%c", refid[i]);
        }
    }
    printf("\n");
    printf("Reference Time: %s", ctime(&time));
 
    close(sockfd);
    return 0;
}
ntpquery.txt ยท Last modified: 2025/01/26 15:15 by admin

Donate Powered by PHP Valid HTML5 Valid CSS Driven by DokuWiki