Professional Documents
Culture Documents
Server:
#include<stdio.h>
#include<sys/types.h>
#include<netdb.h>
#include<sys/socket.h>
#include<netinet/in.h>
#include<strings.h>
#include<stdlib.h>
#define port 6014
int main()
{
int sockfd,newsockfd,client,childpd;
struct sockaddr_in seradd,cli_add;
char *msg="";
time_t t;
if((sockfd=socket(AF_INET,SOCK_STREAM,0))<0)
{
printf("error");
return -1;
}
bzero((char *)&seradd,sizeof(seradd));
seradd.sin_family=AF_INET;
seradd.sin_addr.s_addr=htonl(INADDR_ANY);
seradd.sin_port=htons(port);
}
listen(sockfd,5);
for(;;)
{
client=sizeof(cli_add);
newsockfd=accept(sockfd,(struct sockaddr *)&cli_add,&client);
if(newsockfd<0)
{
printf("error2");
return -1;
}
if((childpd=fork())<0)
{
printf("error4");
return -1;
}
else if (childpd==0)
{
// close(sockfd);
// recv(newsockfd,msg,80,0);
// printf("%s",msg);
time(&t);
msg=ctime(&t);
send(newsockfd,msg,80,0);
close(sockfd);
close(newsockfd);
exit(0);
}
printf("connection");
close(newsockfd);