通过TCP实现NTP服务器

通过TCP实现NTP服务器

头文件:proto.h

#ifndef __PRTOO_H__
#define __PRTOO_H__

#define PORT "8888"   //服务器端口
#define FMT "%lld\r\n"  //输出格式

#endif

服务器端:server.c

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <arpa/inet.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <time.h>
#include <unistd.h>
#include "proto.h"

#define IPSIZE 40

static void func(int fd)   //将获取到的时间戳发送个客户端
{
  FILE *fp = fdopen(fd,"r+");
  fprintf(fp,FMT,(long long)time(NULL));
  fclose(fp);
}

int main()
{
  int ret;
  int lfd,newfd;
  struct sockaddr_in laddr,raddr;
  socklen_t lenth;
  char ip[IPSIZE];

  lfd = socket(AF_INET,SOCK_STREAM,0);  //创建socket
  if(lfd <0)
  {
    perror("socket()");
    exit(1);
  }

  int val =1;
  ret = setsockopt(lfd,SOL_SOCKET,SO_REUSEPORT,&val,sizeof(val));  //设置PORT复用
  if(ret <0)
  {
    perror("setsockopt()");
    exit(1);
  }

  laddr.sin_family = AF_INET;  //初始化结构体
  laddr.sin_port = htons(atoi(PORT));
  inet_pton(AF_INET,"0.0.0.0",&laddr.sin_addr.s_addr);
  ret = bind(lfd,(void *)&laddr,sizeof(laddr));  //绑定端口和IP
  if(ret<0)
  {
    perror("bind()");
    exit(1);
  }

  ret = listen(lfd,200);  //监听最大200个
  if(ret <0)
  {
    perror("listen()");
    exit(1);
  }

  lenth = sizeof(raddr);
  while(1)
  {
    newfd = accept(lfd,(void *)&raddr,&lenth);  //接收新客户端连接
    if(newfd<0)
    {
      perror("accpt()");
      break;
    }

    inet_ntop(AF_INET,&raddr.sin_addr.s_addr,ip,IPSIZE);
    printf("-----IP:%s PORT:%d-----\n",ip,ntohs(raddr.sin_port));  //输出客户端信息
    func(newfd);
  }

  close(lfd);
  exit(0);
}

 

客户端:client.c

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <arpa/inet.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <time.h>
#include <unistd.h>
#include "proto.h"

#define BUFFSIZE 128

int main(int argc, char **argv)
{
  int ret;
  int rfd;
  struct sockaddr_in raddr;
  char buff[BUFFSIZE];
  ssize_t lenth;

  if(argc<2)   //参数判断
  {
    fprintf(stderr,"Usage:%s <server ip>\n",argv[0]);
    exit(1);
  }

  rfd = socket(AF_INET,SOCK_STREAM,0);  //创建socket
  if(rfd <0)
  {
    perror("socket()");
    exit(1);
  }

  raddr.sin_family = AF_INET;   //初始化结构体
  raddr.sin_port = htons(atoi(PORT));
  inet_pton(AF_INET,argv[1],&raddr.sin_addr.s_addr);
  ret = connect(rfd,(void *)&raddr,sizeof(raddr));  //连接服务器
  if(ret <0)
  {
    perror("connect()");
    exit(1);
  }

  memset(buff,0,BUFFSIZE);
  lenth = recv(rfd,buff,BUFFSIZE,0);   //读取数据
  if(lenth<0)
  {
    perror("recv()");
    close(rfd);
    exit(1);
  }

  fprintf(stdout,"TIME = %s",buff);  //输出

  close(rfd);
  exit(0);
}

 

编译文件:Makefile

all:client server

client:client.o
  $(CC) $^ -o $@

server:server.o
  $(CC) $^ -o $@

clean:
  $(RM) *.o server client

 

posted @ 2022-08-10 11:17  *^VV^*  阅读(321)  评论(0编辑  收藏  举报