⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 main.c

📁 linux下的获取Internet time的程式
💻 C
📖 第 1 页 / 共 5 页
字号:
/*  Copyright (C) 1996, 1997, 2000 N.M. Maclaren    Copyright (C) 1996, 1997, 2000 The University of CambridgeThis is a complete SNTP implementation, which was easier to write than to portxntp to a new version of Unix with any hope of maintaining it thereafter.  Itsupports the full SNTP (RFC 2030) client- and server-side challenge-responseand broadcast protocols.  It should achieve nearly optimal accuracy with veryfew transactions, provided only that a client has access to a trusted serverand that communications are not INVARIABLY slow.  As this is the environment inwhich 90-99% of all NTP systems are run ....The specification of this program is:    msntp [ --help | -h | -? ] [ -v | -V | -W ]        [ -B [ period ] | -S | -q [ -f savefile ] |            [ { -r | -a } [ -P prompt ] [ -l lockfile ] ]            [ -c count ] [ -e minerr ][ -E maxerr ]            [ -d delay | -x [ separation ] [ -f savefile ] ]            [ address(es) ] ]    --help, -h and -? all print the syntax of the command.    -v indicates that diagnostic messages should be written to standard error,and -V requests more output for investigating apparently inconsistenttimestamps.  -W requests very verbose debugging output, and will interfere withthe timing when writing to the terminal (because of line buffered output fromC); it is useful only when debugging the source.  Note that the times producedby -V and -W are the corrections needed, and not the error in the local clock.    -B indicates that it should behave as a server, broadcasting time packetsat intervals of 'period' minutes.  Acceptable values of 'period' are from 1 to1440 (a day) and the default is 60.  Naturally, this will work only if theuser has enough privilege.    -S indicates that it should behave as a server, responding to time requests from clients.  Naturally, this will work only if the user has enough privilege.    -q indicates that it will query a savefile that is being maintained byit being run in daemon mode.     The default is that it should behave as a client, and the following optionsare then relevant:    -r indicates that the system clock should be reset by 'settimeofday'.Naturally, this will work only if the user has enough privilege.    -a indicates that the system clock should be reset by 'adjtime'.Naturally, this will work only if the user has enough privilege.    -x indicates that the program should run as a daemon (i.e. forever), andallow for clock drift.    The default is to write the current date and time to the standard output ina format like '1996 Oct 15 20:17:25.123 + 4.567 +/- 0.089 secs', indicating theestimated true (local) time and the error in the local clock.  In daemon mode,it will add drift information in a format like ' + 1.3 +/- 0.1 ppm', anddisplay this at roughly 'separation' intervals.    'minerr' is the maximum ignorable variation between the clocks.  Acceptablevalues are from 0.001 to 1, and the default is 0.1 if 'address' is specifiedand 0.5 otherwise.    'maxerr' is the maximum value of various delays that are deemed acceptable.Acceptable values are from 1 to 60, and the default is 5.  It should sometimesbe increased if there are problems with the network, NTP server or systemclock, but take care.    'prompt' is the maximum clock change that will be made automatically.Acceptable values are from 1 to 3600, and the default is 30.  If the program isbeing run interactively, larger values will cause a prompt.  The value may alsobe 'no', and the change will be made without prompting.    'count' is the maximum number of NTP packets to require.  Acceptable valuesare from 1 to 25 if 'address' is specified and '-x' is not, and from 5 to 25otherwise; the default is 5.  If the maximum isn't enough, you need a betterconsistency algorithm than this program uses.  Don't increase it.    'delay' is a rough limit on the total running time in seconds.  Acceptablevalues are from 1 to 3600, and the default is 15 if 'address' is specified and300 otherwise.    'separation' is the time to wait between calls to the server in minutes if'address' is specified, and the minimum time between broadcast packets if not.Acceptable values are from 1 to 1440 (a day), and the default is 300.    'lockfile' may be used in an update mode to ensure that there is onlyone copy of msntp running at once.  The default is installation-dependent,but will usually be /etc/msntp.pid.    'savefile' may be used in daemon mode to store a record of previouspackets, which may speed up recalculating the drift after msntp has to berestarted (e.g. because of network or server outages).  The default isinstallation-dependent, but will usually be /etc/msntp.state.  Note thatthere is no locking of this file, and using it twice may cause chaos.    'address' is the DNS name or IP number of a host to poll; if no name isgiven, the program waits for broadcasts.  Note that a single component numericaddress is not allowed.For sanity, it is also required that 'minerr' < 'maxerr' < 'delay' (iflistening for broadcasts, 'delay/count' and, in daemon mode, 'separation') and,for sordid Unixish reasons, that 2*'count' < 'delay'.  The last could be fixed,but isn't worth it.  Note that none of the above values are closely linked tothe limits described in the NTP protocol (RFC 1305).  Do not increase thecompiled-in bounds excessively, or the code will fail.The algorithm used to decide whether to accept a correction is whether it wouldseem to improve matters.  Unlike the 'xntp' suite, little attempt is made tohandle really knotted scenarios, and diagnostics are written to standard error.In non-daemon client mode, it is intended to be run as a command or in a 'cron'job.  Unlike 'ntpdate', its default mode is simply to display the clock error.It assumes that floating-point arithmetic is tolerably efficient, which is truefor even the cheapest personal computer nowadays.  If, however, you want toport this to a toaster, you may have problems!In its terminating modes, its return code is EXIT_SUCCESS if the operation wascompleted successfully and EXIT_FAILURE otherwise.In server or daemon mode, it runs for ever and stops with a return codeEXIT_FAILURE only after a severe error.  Commonly, two server processes will berun, one with each of the -B and -S options.  In daemon mode, it will fail ifthe server is inaccessible for a long time or seriously sick, and will needmanual restarting.WARNING: this program has reached its 'hack count' and needs restructuring,badly.  Perhaps the worst code is in run_daemon().  You are advised not tofiddle unless you really have to. */#include "header.h"#include <limits.h>#include <float.h>#include <math.h>#define MAIN#include "kludges.h"#undef MAIN/* defined in libmsntp.c */extern int libmsntp_errno;extern const char *libmsntp_strerror;/* NTP definitions.  Note that these assume 8-bit bytes - sigh.  There islittle point in parameterising everything, as it is neither feasible noruseful.  It would be very useful if more fields could be defined asunspecified.  The NTP packet-handling routines contain a lot of extraassumptions. */#define JAN_1970   2208988800.0        /* 1970 - 1900 in seconds */#define NTP_SCALE  4294967296.0        /* 2^32, of course! */#define NTP_PACKET_MIN       48        /* Without authentication */#define NTP_PACKET_MAX       68        /* With authentication (ignored) */#define NTP_DISP_FIELD        8        /* Offset of dispersion field */#define NTP_REFERENCE        16        /* Offset of reference timestamp */#define NTP_ORIGINATE        24        /* Offset of originate timestamp */#define NTP_RECEIVE          32        /* Offset of receive timestamp */#define NTP_TRANSMIT         40        /* Offset of transmit timestamp */#define NTP_LI_FUDGE          0        /* The current 'status' */#define NTP_VERSION           3        /* The current version */#define NTP_VERSION_MAX       4        /* The maximum valid version */#define NTP_STRATUM          15        /* The current stratum as a server */#define NTP_STRATUM_MAX      15        /* The maximum valid stratum */#define NTP_POLLING           8        /* The current 'polling interval' */#define NTP_PRECISION         0        /* The current 'precision' - 1 sec. */#define NTP_ACTIVE            1        /* NTP symmetric active request */#define NTP_PASSIVE           2        /* NTP symmetric passive response */#define NTP_CLIENT            3        /* NTP client request */#define NTP_SERVER            4        /* NTP server response */#define NTP_BROADCAST         5        /* NTP server broadcast */#define NTP_INSANITY     3600.0        /* Errors beyond this are hopeless */#define RESET_MIN            15        /* Minimum period between resets */#define ABSCISSA            3.0        /* Scale factor for standard errors *//* Local definitions and global variables (mostly options).  These are all ofthe quantities that control the main actions of the program.  The first three are the only ones that are exported to other modules. */const char *argv0 = NULL;              /* For diagnostics only - not NULL */int verbose = 0,                       /* Default = 0, -v = 1, -V = 2, -W = 3 */    operation = 0;                     /* Defined in header.h - see action */const char *lockname = NULL;           /* The name of the lock file */#define COUNT_MAX          25          /* Do NOT increase this! */#define WEEBLE_FACTOR     1.2          /* See run_server() and run_daemon() */#define ETHERNET_MAX        5          /* See run_daemon() and run_client() */#define action_display      1          /* Just display the result */#define action_reset        2          /* Reset using 'settimeofday' */#define action_adjust       3          /* Reset using 'adjtime' */#define action_broadcast    4          /* Behave as a server, broadcasting */#define action_server       5          /* Behave as a server for clients */#define action_query        6          /* Query a daemon savefile */#define save_read_only      1          /* Read the saved state only */#define save_read_check     2          /* Read and check it */#define save_write          3          /* Write the saved state */#define save_clear          4          /* Clear the saved state */static const char version[] = VERSION; /* For reverse engineering :-) */int action = 0,                        /* Defined above - see operation */    period = 0,                        /* -B value in seconds (broadcast) */    count = 0,                         /* -c value in seconds */    delay = 0,                         /* -d or -x value in seconds */    attempts = 0,                      /* Packets transmitted up to 2*count */    waiting = 0,                       /* -d/-c except for in daemon mode */    locked = 0;                        /* set_lock(1) has been called */double outgoing[2*COUNT_MAX],          /* Transmission timestamps */    minerr = 0.0,                      /* -e value in seconds */    maxerr = 0.0,                      /* -E value in seconds */    prompt = 0.0,                      /* -p value in seconds */    dispersion = 0.0;                  /* The source dispersion in seconds */static FILE *savefile = NULL;          /* Holds the data to restart from *//* The unpacked NTP data structure, with all the fields even remotely relevantto SNTP. */typedef struct NTP_DATA {    unsigned char status, version, mode, stratum, polling, precision;    double dispersion, reference, originate, receive, transmit, current;} ntp_data;/* The following structure is used to keep a record of packets in daemon mode;it contains only the information that is actually used for the drift and errorcalculations. */typedef struct {    double dispersion, weight, when, offset, error;} data_record;void fatal (int errnum, const char *message, const char *insert) {/* Set libmsntp_errno and libmsntp_strerror. */    libmsntp_errno = errnum;    if (message != NULL)        libmsntp_strerror = message;}void syntax (int halt) {/* The standard, unfriendly Unix error message.  Some errors are diagnosed morehelpfully.  This is called before any files or sockets are opened. */    fprintf(stderr,"Syntax: %s [ --help | -h | -? ] [ -v | -V | -W ] \n",argv0);    fprintf(stderr,"    [ -B period | -S | -q [ -f savefile ] |\n");    fprintf(stderr,"        [ { -r | -a } [ -P prompt ] [ -l lockfile ] ]\n");    fprintf(stderr,"            [ -c count ] [ -e minerr ] [ -E maxerr ]\n");    fprintf(stderr,"            [ -d delay | -x [ separation ] ");    fprintf(stderr,"[ -f savefile ] ]\n");    fprintf(stderr,"        [ address(es) ] ]\n");    if (halt) exit(EXIT_FAILURE);}void display_data (ntp_data *data) {/* This formats the essential NTP data, as a debugging aid. */    fprintf(stderr,"sta=%d ver=%d mod=%d str=%d pol=%d dis=%.6f ref=%.6f\n",        data->status,data->version,data->mode,data->stratum,data->polling,        data->dispersion,data->reference);    fprintf(stderr,"ori=%.6f rec=%.6f\n",data->originate,data->receive);    fprintf(stderr,"tra=%.6f cur=%.6f\n",data->transmit,data->current);}void display_packet (unsigned char *packet, int length) {/* This formats a possible packet very roughly, as a debugging aid. */    int i;    if (length < NTP_PACKET_MIN || length > NTP_PACKET_MAX) return;    for (i = 0; i < length; ++i) {        if (i != 0 && i%32 == 0)            fprintf(stderr,"\n");         else if (i != 0 && i%4 == 0)             fprintf(stderr," ");         fprintf(stderr,"%.2x",packet[i]);    }    fprintf(stderr,"\n");}void pack_ntp (unsigned char *packet, int length, ntp_data *data) {/* Pack the essential data into an NTP packet, bypassing struct layout andendian problems.  Note that it ignores fields irrelevant to SNTP. */    int i, k;    double d;    memset(packet,0,(size_t)length);    packet[0] = (data->status<<6)|(data->version<<3)|data->mode;    packet[1] = data->stratum;    packet[2] = data->polling;    packet[3] = data->precision;    d = data->originate/NTP_SCALE;    for (i = 0; i < 8; ++i) {        if ((k = (int)(d *= 256.0)) >= 256) k = 255;        packet[NTP_ORIGINATE+i] = k;        d -= k;    }    d = data->receive/NTP_SCALE;    for (i = 0; i < 8; ++i) {        if ((k = (int)(d *= 256.0)) >= 256) k = 255;        packet[NTP_RECEIVE+i] = k;        d -= k;    }    d = data->transmit/NTP_SCALE;

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -