公共头文件
include <stdio.h>
include <stdlib.h>
include <string.h>
include <time.h>
include <sys/types.h>
include <sys/socket.h>
include <netinet/in.h>
include <unistd.h>
include <fcntl.h>
define MAX_LISTEN_QUE 5
server.c
include "socket_includes.h"
int main(int argc, char *argv[])
{
int listenfd, sockfd, opt = 1;
struct sockaddr_in server, client;
char buf[200];
socklen_t len;
time_t timep;
int ret;
listenfd = socket(AF_INET, SOCK_STREAM, 0);
if(listenfd < 0){
perror("Create socket fail.");
return -1;
}
if((ret = setsockopt(listenfd, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt))) < 0){
perror("Error, set socket reuse addr failed");
return -1;
}
bzero(&server, sizeof(server));
server.sin_family = AF_INET;
server.sin_port = htons(8888);
server.sin_addr.s_addr = htonl(INADDR_ANY);
len = sizeof(struct sockaddr);
if(bind(listenfd, (struct sockaddr *)&server, len)<0){
perror("bind error.");
return -1;
}
listen(listenfd, MAX_LISTEN_QUE);
while(1)
{
sockfd = accept(listenfd, (struct sockaddr *)&client, &len);
if(sockfd < 0){
perror("accept error.");
return -1;
}
timep = time(NULL);
snprintf(buf, sizeof(buf), "%s", ctime(&timep));
write(sockfd, buf, strlen(buf));
printf("Bytes:%lu\n", strlen(buf));
printf("sockfd=%d\n", sockfd);
close(sockfd);
}
return 0;
}
include "socket_includes.h"
int main(int argc, char *argv[])
{
int sockfd;
struct sockaddr_in servaddr;
char buf[100];
int bytes;
if(( sockfd = socket(AF_INET,SOCK_STREAM,0)) < 0 )
{
perror("socket error");
return -1;
}
bzero(&servaddr, sizeof(servaddr));
servaddr.sin_family = AF_INET;
servaddr.sin_addr.s_addr= inet_addr("127.0.0.1");
servaddr.sin_port = htons(8888);
if( connect(sockfd,(struct sockaddr*)&servaddr,sizeof(servaddr)) < 0 )
{
perror("connect error");
return 0;
}
bytes = read(sockfd, buf, 100);
if(bytes < 0){
printf("Error, read failed.\n");
return -1;
}
if(0 == bytes){
printf("Server close connection.\n");
return -1;
}
printf("Read bytes %d\n", bytes);
printf("Time:%s\n", buf);
close(sockfd);
}