1 Star 0 Fork 0

chu凯旋/socket test

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
该仓库未声明开源许可证文件(LICENSE),使用请关注具体项目描述及其代码上游依赖。
克隆/下载
dateserver.c 2.11 KB
一键复制 编辑 原始数据 按行查看 历史
chu凯旋 提交于 2021-12-20 03:41 . add dateserver.c.
#include <stdio.h>
#include <unistd.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <sys/wait.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <stdlib.h>
#include <time.h>
#include <string.h>
#define MAXLINE 200
#define RIO_BUFSIZE 8192
typedef struct{
int rio_fd;
int rio_cnt;
char *rio_bufptr;
char rio_buf[RIO_BUFSIZE];
}rio_t;
typedef struct sockaddr SA;
typedef struct{
int tm_sec;
int tm_min;
int tm_hour;
int tm_mday;
int tm_mon;
int tm_year;
int tm_wday;
int tm_yday;
int tm_isdst;
}tm;
void sigchld_handler(int sig){
pid_t pid;
int stat;
while((pid = waitpid(-1,&stat,WNOHANG))>0){
printf("child %d terminated\n",pid);
}
return;
}
int main(int argc,char **argv){
int listenfd,connfd,port,clientlen;
struct sockaddr_in clientaddr;
struct hostent *hp;
char *haddrp;
char sbuf[MAXLINE];
char rbuf[MAXLINE];
rio_t rio;
time_t lt;
tm *local;
char str1[MAXLINE]="客户端IP:";
char str2[MAXLINE]="服务器实现者学号:";
char str3[MAXLINE]="当前时间:";
if(argc != 2){
fprintf(stderr,"usage:%s <port>\n",argv[0]);
exit(0);
}
port = atoi(argv[1]);
signal(SIGCHLD,sigchld_handler);
listenfd = open_listenfd(port);
while(1){
clientlen = sizeof(clientaddr);
connfd = accept(listenfd,(SA *)&clientaddr,&clientlen);
hp = gethostbyaddr((const char*)&clientaddr.sin_addr.s_addr,
sizeof(clientaddr.sin_addr.s_addr),AF_INET);
haddrp = inet_ntoa(clientaddr.sin_addr);
printf("server connected to %s (%s)\n",hp->h_name,haddrp);
if(fork() == 0){
close(listenfd);
lt = time(NULL);
local = localtime(&lt);
strftime(sbuf,64, %H:%M:%S",local);
send(connfd,sbuf,MAXLINE,0);
close(connfd);
exit(0);
}
close(connfd);
}
}
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/chu-triumph/socket-test.git
git@gitee.com:chu-triumph/socket-test.git
chu-triumph
socket-test
socket test
master

搜索帮助