公共头文件:
#pragma once #include<stdio.h> #include<stdint.h> #include<string.h> #include<unistd.h> #include<arpa/inet.h> #include<stdlib.h> #include<time.h> #include<stdbool.h> #include<signal.h> #define SERVERPORT 1989 #define FTM_STAMP "%lld\r\n" #define lv_exit(str)\ perror(str);\ exit(1);
服务端代码:
#include"proto.h" static void serverjob(int confd){ char buf[512]={0}; int len=sprintf(buf,FTM_STAMP,(long long)time(NULL)); if(send(confd,buf,len,0)<0){ perror("send"); exit(1); } } int main(int argc, char const *argv[]) { int sfd=socket(AF_INET,SOCK_STREAM,0); if(sfd<0){ perror("socket"); exit(1); } struct sockaddr_in seraddr; seraddr.sin_family=AF_INET; seraddr.sin_port=htons(SERVERPORT); seraddr.sin_addr.s_addr=inet_addr("192.168.244.154"); int val=1; if(setsockopt(sfd,SOL_SOCKET,SO_REUSEADDR,&val,sizeof val)<0){ perror("setsockopt"); exit(1); } if(bind(sfd,(void*)&seraddr,sizeof seraddr)<0){ perror("bind"); exit(1); } if(listen(sfd,10)<0){ perror("listen"); exit(1); } struct sockaddr_in cliaddr; socklen_t clilen=sizeof cliaddr; while (1) { int confd=accept(sfd,(void*)&cliaddr,&clilen); if(confd<0){ perror("accept"); exit(1); } signal(SIGCHLD,SIG_IGN); //防止产生僵尸进程 pid_t pid=fork(); if (pid<0) { perror("fork"); exit(1); } if(pid==0){ close(sfd); printf("client %s %d\n",inet_ntoa(cliaddr.sin_addr),ntohs(cliaddr.sin_port)); serverjob(confd); close(confd); exit(0); } close(confd); } close(sfd); return 0; }
客户端代码:
#include "proto.h" int main(int argc, char const *argv[]) { int sfd = socket(AF_INET, SOCK_STREAM, 0); if (sfd < 0) { perror("socket"); exit(1); } struct sockaddr_in seraddr; seraddr.sin_family = AF_INET; seraddr.sin_port = htons(SERVERPORT); seraddr.sin_addr.s_addr = inet_addr("192.168.244.154"); if (connect(sfd, (void *)&seraddr, sizeof seraddr) < 0) { perror("connect"); exit(1); } FILE *fp = fdopen(sfd, "r+"); if (fp == NULL) { perror("fdopen"); exit(1); } long long stamp; if (fscanf(fp, FTM_STAMP, &stamp) < 1) { fprintf(stderr, "Bad format!\n"); } else { fprintf(stdout, "stamp=%lld\n", stamp); } fclose(fp); return 0; }
注意:signal(SIGCHLD,SIG_IGN); //防止产生僵尸进程
0.0分
0 人评分