server_delay.c
资源名称:NetProg03.rar [点击查看]
上传用户:gzxinfenfa
上传日期:2015-02-06
资源大小:279k
文件大小:2k
源码类别:
ICQ弱点检测代码
开发平台:
Visual C++
- /* 服务器处理延时
- * 用法:
- * ./server port delay_seconds &
- */
- #include <stdio.h>
- #include <stdlib.h>
- #include <string.h>
- #include <sys/socket.h>
- #include <netinet/in.h>
- #include <arpa/inet.h>
- #include <unistd.h>
- #include <sys/types.h>
- #define MAXDATASIZE 128
- #define BACKLOG 5
- int main(int argc,char **argv){
- int sockfd,new_fd,nbytes,sin_size;
- char buf[MAXDATASIZE];
- struct sockaddr_in srvaddr,clientaddr;
- unsigned short port;
- int on=1;
- int delay = 3;
- if(argc!=3){
- printf("usage:%s port delayn", argv[0]);
- return 1;
- }
- port = atoi(argv[1]);
- delay = atoi(argv[2]);
- if( delay < 0 )
- {
- printf("Delay time should great than 0.n");
- return 1;
- }
- //1.创建网络端点
- sockfd=socket(AF_INET,SOCK_STREAM,0);
- if(sockfd == -1){
- perror("can't create socketn");
- exit(1);
- }
- setsockopt(sockfd,SOL_SOCKET,SO_REUSEADDR,&on,sizeof(on));
- //填充地址
- bzero(&srvaddr,sizeof(srvaddr));
- srvaddr.sin_family = AF_INET;
- srvaddr.sin_port = htons(port);
- srvaddr.sin_addr.s_addr = htonl(INADDR_ANY);
- //2.绑定服务器地址和端口
- if(bind(sockfd,(struct sockaddr *)&srvaddr,sizeof(struct sockaddr))==-1){
- perror("bind errorn");
- exit(1);
- }
- //3. 监听端口
- if(listen(sockfd,BACKLOG)==-1){
- perror("listen errorn");
- exit(1);
- }
- for(;;){ //循环/迭代式服务器
- //4.接受客户端连接
- sin_size = sizeof(struct sockaddr_in);
- new_fd = accept(sockfd,(struct sockaddr *)&clientaddr,&sin_size);
- if(new_fd == -1){
- perror("accept error:");
- printf("Server abort.n");
- break;
- }
- printf("Server>> client addr:%s %dn",
- inet_ntoa(clientaddr.sin_addr),
- ntohs(clientaddr.sin_port));
- //5.接收请求
- nbytes = read(new_fd,buf,MAXDATASIZE);
- buf[nbytes]=' ';
- printf("Server>> client:%sn",buf);
- sleep(delay); // 模拟延时
- //6.回送响应
- sprintf(buf,"welcome!");
- write(new_fd,buf,strlen(buf));
- //关闭socket
- close(new_fd);
- }
- close(sockfd); // 关闭用来监听的socket
- return 0;
- }