C实现一个NTP客户端,可以从指定IP的NTP服务器获取时间戳
参考::https://blog.csdn.net/dosthing/article/details/81588219
下面的代码测试通过
头文件
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/ioctl.h>
#include <sys/socket.h>
#include <sys/wait.h>
#include <sys/time.h>
#include <netdb.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <pthread.h>
#include <dirent.h>
#include <time.h>
#include <fcntl.h>
#include <errno.h> #define debugprintf 1
#ifdef debugprintf
#define debugpri(mesg, args...) fprintf(stderr, "[NetRate print:%s:%d:] " mesg "\n", __FILE__, __LINE__, ##args)
#else
#define debugpri(mesg, args...)
#endif #define JAN_1970 0x83aa7e80
#define NTPFRAC(x) (4294 * (x) + ((1981 * (x))>>11))
#define USEC(x) (((x) >> 12) - 759 * ((((x) >> 10) + 32768) >> 16))
#define Data(i) ntohl(((unsigned int *)data)[i])
#define LI 0
#define VN 3
#define MODE 3
#define STRATUM 0
#define POLL 4
#define PREC -6 struct NtpTime
{
unsigned int coarse;
unsigned int fine;
}; void sendPacket(int fd);
void getNewTime(unsigned int *data,struct timeval *ptimeval);
double getNtpTime(char * pIP);
源文件
#include "ntp1_so.h"
int main()
{
char myIP[20]="52.175.49.4"; //time.windows.com
double currentTime = getNtpTime(myIP);
printf("currentTime=%f\n",currentTime);
return 0;
}
void sendPacket(int fd)
{
unsigned int data[];
struct timeval now; if (sizeof(data) != )
{
fprintf(stderr,"size error\n");
return;
} memset((char*)data, , sizeof(data));
data[] = htonl((LI << ) | (VN << ) | (MODE << ) | (STRATUM << ) | (POLL << ) | (PREC & 0xff));
data[] = htonl(<<);
data[] = htonl(<<);
gettimeofday(&now, NULL);
data[] = htonl(now.tv_sec + JAN_1970);
data[] = htonl(NTPFRAC(now.tv_usec));
send(fd, data, , );
} void getNewTime(unsigned int *data,struct timeval *ptimeval)
{
struct NtpTime trantime;
trantime.coarse = Data();
trantime.fine = Data(); ptimeval->tv_sec = trantime.coarse - JAN_1970;
ptimeval->tv_usec = USEC(trantime.fine);
} double getNtpTime(char * pIP)
{
int sockfd;
struct sockaddr_in addr_src,addr_dst;
fd_set fds;
int ret;
int recv_len;
unsigned int buf[];
memset(buf,,sizeof(buf));
int addr_len;
int count = ; struct timeval recvtv;
struct timeval *ptimeval;
double offset;
struct timeval timeout; addr_len = sizeof(struct sockaddr_in);
//local
memset(&addr_src, , addr_len);
addr_src.sin_family = AF_INET;
addr_src.sin_addr.s_addr = htonl(INADDR_ANY);
addr_src.sin_port = htons();
//remote
memset(&addr_dst, , addr_len);
addr_dst.sin_family = AF_INET;
addr_dst.sin_addr.s_addr=inet_addr(pIP);
addr_dst.sin_port = htons();//ntp默认端口123 if(-==(sockfd = socket(AF_INET,SOCK_DGRAM,IPPROTO_UDP)))
{
debugpri("create socket error!\n");
return -;
} ret = bind(sockfd, (struct sockaddr*)&addr_src, addr_len);
if(-==ret)
{
debugpri("bind error!\n");
close(sockfd);
return -;
} ret = connect(sockfd, (struct sockaddr*)&addr_dst, addr_len);
if(-==ret)
{
debugpri("connect error!\n");
close(sockfd);
return -;
} sendPacket(sockfd);
while (count < )
{
FD_ZERO(&fds);
FD_SET(sockfd, &fds); timeout.tv_sec = ;
timeout.tv_usec = ;
ret = select(sockfd + , &fds, NULL, NULL, &timeout);
if ( == ret)
{
count++;
debugpri("ret == 0\n");
sendPacket(sockfd);
usleep(*);
continue;
}
if(FD_ISSET(sockfd, &fds))
{
recv_len = recvfrom(sockfd, buf, sizeof(buf), , (struct sockaddr *)&addr_dst, (socklen_t*)&addr_len);
if(-==recv_len)
{
debugpri("recvfrom error\n");
close(sockfd);
return -;
}
else if(recv_len > )
{
debugpri("receiv data\n");
getNewTime(buf,ptimeval);
debugpri("sec = %d usec = %d",ptimeval->tv_sec ,ptimeval->tv_usec); break;
}
}
else
{
debugpri("count %d \n",count);
usleep(*);
count ++;
}
}
if(count >=)
{
debugpri("getNewTime timeout ! \n");
close(sockfd);
return -;
}
close(sockfd);
return ptimeval->tv_sec;
}
C实现一个NTP客户端,可以从指定IP的NTP服务器获取时间戳的更多相关文章
- 授权指定ip访问mysql 服务器
授权指定ip访问访问 授权ROOT使用密码1234从应用服务器主机连接到mysql服务器 mysql> GRANT ALL PRIVILEGES ON *.* TO 'root'@'xxx. ...
- 指定ip地址登陆服务器
[root@localhost ~]# cat /etc/hosts.allow ## hosts.allow This file contains access rules which are ...
- 003.NTP客户端配置
一 NTP客户端同步方式 ntpdate定时任务同步 ntp服务同步 二 ntpdate定时任务同步 2.1 安装ntp软件 [root@client ~]# yum -y install ntp # ...
- 搭建DHCP服务实现动态分配IP地址-NTP网络时间同步
本节所讲内容: DHCP服务器工作原理 使用DHCP为局域网中的机器分配IP地址 使用DHCP为服务器分配固定IP地址 ntpdate加计划任务同步服务器时间 实验环境: 服务端:xuegod63 ...
- linux服务器ntp客户端配置【转】
转自:https://www.cnblogs.com/kerrycode/archive/2015/08/20/4744804.html 在Linux系统中,为了避免主机时间因为在长时间运行下所导致的 ...
- 一个服务器上面配置多个IP ,实现指定IP的域名请求
//配置多个IP命名using System.Net; //********************************************************************** ...
- 使用c++实现一个FTP客户端(一)
之前使用c++实现了一个FTP客户端,在这里做一些记录. 一.需要注意的几点 ①FTP是一种文件传输协议,基于TCP,所以客户端与服务器建立的连接是可靠.安全的,并且要经过三次握手的过程. ②FTP传 ...
- [Swift通天遁地]四、网络和线程-(13)创建一个Socket客户端
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★➤微信公众号:山青咏芝(shanqingyongzhi)➤博客园地址:山青咏芝(https://www.cnblogs. ...
- 与众不同 windows phone (38) - 8.0 关联启动: 使用外部程序打开一个文件或URI, 关联指定的文件类型或协议
[源码下载] 与众不同 windows phone (38) - 8.0 关联启动: 使用外部程序打开一个文件或URI, 关联指定的文件类型或协议 作者:webabcd 介绍与众不同 windows ...
随机推荐
- 专业英语词汇(Java)
abstract (关键字) 抽象 ['.bstr.kt] access vt.访问,存取 ['.kses]‘(n.入口, ...
- spring ioc xml配置
一个完整的spring xml配置:是把action,service,dao以及其它的资源性配置(如basedao)和公共性配置(如连接数据库)配置在resource.xml中,这样就有四个xml配置 ...
- c# 结构体 集合 复习
添加5个学生的信息到集合中,每个学生都有:学号,姓名,成绩,3个内容,添加完毕后将学生的分数从高到低排列并打印出来,使用结构体 using System; using System.Collectio ...
- Java.sql.SQLException: 无效的列类型: 1111
org.mybatis.spring.MyBatisSystemException: nested exception is org.apache.ibatis.type.TypeException: ...
- Cannot create inner bean '(inner bean)#67f903b5' of typ
严重: Context initialization failedorg.springframework.beans.factory.BeanCreationException: Error crea ...
- oracle存储过程-获取错误信息
dbms_output.put_line('code:' || sqlcode); dbms_output.put_line('errm:' || sqlerrm); dbms_output.put_ ...
- keras—多层感知器MLP—IMDb情感分析
import urllib.request import os import tarfile from keras.datasets import imdb from keras.preprocess ...
- android mapView
1.Because the Maps library is not a part of the standard Android library, you must declare it in the ...
- Petya and Array (权值线段树+逆序对)
Petya and Array http://codeforces.com/problemset/problem/1042/D time limit per test 2 seconds memory ...
- DirectFB编程
一.简介 DirectFB是一个轻量级的提供硬件图形加速,输入设备处理和抽象的图形库,它集成了支持半透明的视窗系统以及在LinuxFramebuffer驱动之上的多层显示.它是一个用软件封装当前硬件无 ...