#include <stdio.h>
#include <sys/socket.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <stdlib.h>
#include <time.h>
#include <strings.h>
#include <errno.h>
int main (int argc,char * argv[])
{
int servfd,clifd;
struct sockaddr_in servaddr,cliaddr;
if((servfd=socket(AF_INET,SOCK_STREAM,0))<0)
{
printf("Create socket error!\n");
return -1;
}
bzero(&servaddr,sizeof(servaddr));
servaddr.sin_family=AF_INET;
servaddr.sin_port=htons(5000);
servaddr.sin_addr.s_addr=htonl(INADDR_ANY); //inet_addr("192.168.0.1");
int option=1;
setsockopt(servfd,SOL_SOCKET,SO_REUSEADDR,(char *)&option,sizeof(option));
struct linger li;
li.l_onoff=1;
li.l_linger=1;
setsockopt(servfd,SOL_SOCKET,SO_LINGER,(char *)&li,sizeof(li));
if(bind(servfd,(struct sockaddr * )&servaddr,sizeof(servaddr))<0)
{
perror("bind to port 5000 failure");
return -1;
}
if(listen(servfd,10)<0)
{
perror("listen error");
return -1;
}
int flags = fcntl(servfd, F_GETFL, 0);
fcntl(servfd, F_SETFL, flags | O_NONBLOCK);
while(1)
{
socklen_t len;
len=sizeof(cliaddr);
clifd=accept(servfd,(struct sockaddr *)&cliaddr,&len);
if(clifd < 0)
{
if (errno==EAGAIN || errno == EWOULDBLOCK)
{
usleep(10000);
continue;
}
else
{
perror("call accept error");
break;
}
}
char szIp[17];
bzero(szIp,17);
inet_ntop(AF_INET,&cliaddr.sin_addr,szIp,16);
printf("from client IP:%s,Port:%d\n",szIp,ntohs(cliaddr.sin_port));
char buf[256];
time_t t;
time(&t);
int datalen=sprintf(buf,"Server:%u\n",(unsigned int)t);
send(clifd,buf,datalen,0);
close(clifd);
}
close(servfd);
return 0;
}
|