Chinaunix首页 | 论坛 | 博客
  • 博客访问: 858002
  • 博文数量: 150
  • 博客积分: 5123
  • 博客等级: 大校
  • 技术积分: 1478
  • 用 户 组: 普通用户
  • 注册时间: 2008-11-06 10:03
文章分类

全部博文(150)

文章存档

2011年(2)

2010年(139)

2009年(9)

分类: C/C++

2010-08-29 17:57:22



#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;
}


阅读(8857) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~