Chinaunix首页 | 论坛 | 博客
  • 博客访问: 128031
  • 博文数量: 30
  • 博客积分: 972
  • 博客等级: 中士
  • 技术积分: 332
  • 用 户 组: 普通用户
  • 注册时间: 2012-02-08 10:04
文章分类

全部博文(30)

文章存档

2012年(30)

分类: 系统运维

2012-07-09 20:02:44


 

点击(此处)折叠或打开

  1. #include<stdio.h>
  2. #include<unistd.h>
  3. #include<string.h>
  4. #include<sys/socket.h>
  5. #include<netinet/in.h>
  6. #include<arpa/inet.h>
  7. #include<sys/types.h>
  8. #include<fcntl.h>
  9. #include<sys/stat.h>
  10. #include<stdlib.h>
  11. #include<pthread.h>
  12. void *client_handler(void *arg)
  13. {
  14.  int fd,size;
  15.  char temp[500]="";
  16.  int client_fd = (int)arg;
  17.  char buf[400]="",op_file[50]="";
  18.  char head[]="HTTP/1.1 200 OK\r\n"\
  19.     "Content-Type: text/html\r\n"\
  20.     "\r\n";
  21.   
  22.  char err[]= "HTTP/1.1 404 Not Found\r\n" \
  23.     "Content-Type: text/html\r\n" \
  24.     "\r\n" \
  25.     "File not found ";
  26.     
  27.  read(client_fd,buf,sizeof(buf));
  28.  printf("buf==%s\n",buf);
  29.  sscanf(buf,"GET /%s HTTP/1.1",op_file);
  30.  printf("op_file==%s\n",op_file);
  31.  fd=open(op_file,O_RDONLY);
  32.  if(fd > 0)
  33.  {
  34.   printf("open sucess\n");
  35.   write(client_fd,head,strlen(head));
  36.   while((size=read(fd,temp,500)) > 0 )
  37.    {
  38.    write(client_fd,temp,size);
  39.    bzero(temp,sizeof(temp));
  40.    }
  41.  }
  42.  if(fd < 0)
  43.  {
  44.   printf("open failed\n");
  45.   if( strcmp(op_file,"HTTP/1.1") || strcmp(op_file,"favicon.ico"))
  46.   write(client_fd,err,strlen(err));
  47.  }
  48.  close(fd);
  49.  close(client_fd);
  50.  return NULL;
  51. }
  52. int main(void)
  53. {
  54.  int listen_fd,conn_fd;
  55.  unsigned short port=6000;
  56.  pthread_t tid;
  57.  char ip[INET_ADDRSTRLEN]="";
  58.  struct sockaddr_in server_addr,client_addr;
  59.  socklen_t str_len = sizeof(client_addr);

  60.  bzero(&server_addr,sizeof(struct sockaddr_in));
  61.  bzero(&client_addr,sizeof(struct sockaddr_in));


  62.  server_addr.sin_family = AF_INET;
  63.  server_addr.sin_port = htons(port);
  64.  server_addr.sin_addr.s_addr = htonl(INADDR_ANY);

  65.  listen_fd = socket(AF_INET,SOCK_STREAM,0);

  66.  if((bind(listen_fd,(struct sockaddr*)&server_addr,sizeof(struct sockaddr))) != 0)
  67.  {
  68.   perror("bind");
  69.   exit(-1);
  70.  }

  71.  listen(listen_fd,10);

  72.  while(1)
  73.  {
  74.  conn_fd = accept(listen_fd,(struct sockaddr*)&client_addr,&str_len);
  75.  inet_ntop(AF_INET,&client_addr,ip,INET_ADDRSTRLEN);
  76.  printf("Client ip:%s\n",ip);
  77.  if(conn_fd < 0)
  78.   {
  79.   perror("accept");
  80.   exit(-1);
  81.   }
  82.  pthread_create(&tid,NULL,client_handler,(void *)conn_fd);
  83.  }
  84.  close(listen_fd);
  85. }


 

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

vince0432012-07-18 11:37:39

不错  上个学期末,修了课程嵌入式系统设计,最后要交一个 多用户文件共享系统 的大作业  也学习了下网编