proto.h
#ifndef PROTO_H_
#define PROTO_H_
#define SERVERPORT "2016"
#define FMT_STAMP "%lld\r\n"
#endif
client.c
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include "proto.h"
int main(int argc,char **argv)
{
int sd;
sd = socket(AF_INET,SOCK_STREAM,0);
struct sockaddr_in raddr;
long long stamp;
if(argc < 2)
{
fprintf(stderr,"Usage....\n");
exit(1);
}
if(sd < 0)
{
perror("socket()");
exit(1);
}
// bind();
raddr.sin_family = AF_INET;
raddr.sin_port = htons(atoi(SERVERPORT));
inet_pton(AF_INET,argv[1],&raddr.sin_addr);
if(connect(sd,(void *)&raddr,sizeof(raddr)) <0)
{
perror("connect()");
exit(1);
}
//UNIX 一切皆文件
FILE * fp;
fp = fdopen(sd,"r");
if(fp == NULL)
{
perror("fdopen()");
exit(1);
}
if(fscanf(fp,FMT_STAMP,&stamp) <1)
{
fprintf(stderr,"Bad format!\n");
}
else
{
fprintf(stdout,"stamp = %lld\n",stamp);
}
//recv();
//close();
exit(0);
}
server.c
#include <stdlib.h>
#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <string.h>
#include "proto.h"
#define IPSTRSIZE 40
#define BUFSIZE 1024
#define PROCNUM 4
static void server_loop(int sd);
static void server_job(int sd)
{
char buf[BUFSIZE];
int len;
len = sprintf(buf,FMT_STAMP,(long long)time(NULL));
if(send(sd,buf,len,0)<0)
{
perror("send()");
exit(1);
}
}
int main()
{
int sd;
struct sockaddr_in laddr,raddr;
sd = socket(AF_INET,SOCK_STREAM,0);
if(sd < 0)
{
perror("socket()");
exit(1);
}
int val = 1;
if(setsockopt(sd,SOL_SOCKET,SO_REUSEADDR,&val,sizeof(val))<0)
{
perror("setsockopt()");
exit(1);
}
laddr.sin_family = AF_INET;
laddr.sin_port = htons(atoi(SERVERPORT));
inet_pton(AF_INET,"0.0.0.0",&laddr.sin_addr);
if(bind(sd,(void *)&laddr,sizeof(laddr))<0)
{
perror("bind()");
exit(1);
}
if(listen(sd,10)<0)
{
perror("listen()");
exit(1);
}
pid_t pid;
int i;
for(i =0;i<PROCNUM;i++)
{
pid = fork();
if(pid < 0)
{
perror("fork()");
exit(1);
}
if(pid == 0)
{
server_loop(sd);
exit(0);
}
}
for(i=0;i<PROCNUM;i++)
{
wait(NULL);
}
close(sd);
exit(0);
}
static void server_loop(int sd)
{
struct sockaddr_in raddr;
int newsd;
char ipstr[IPSTRSIZE];
socklen_t raddr_len;
raddr_len = sizeof(socklen_t);
while(1)
{
newsd = accept(sd,(void *)&raddr,&raddr_len);
if(newsd <0)
{
perror("accept()");
exit(1);
}
inet_ntop(AF_INET,&raddr.sin_addr,ipstr,IPSTRSIZE);
printf("[%d]Client: %s:%d\n",getpid(),ipstr,ntohs(raddr.sin_port));
server_job(newsd);
close(newsd);
}
close(sd);
}