Chinaunix首页 | 论坛 | 博客
  • 博客访问: 51082
  • 博文数量: 36
  • 博客积分: 2000
  • 博客等级: 大尉
  • 技术积分: 390
  • 用 户 组: 普通用户
  • 注册时间: 2009-05-23 15:42
文章分类
文章存档

2011年(1)

2009年(35)

我的朋友
最近访客

分类: 系统运维

2009-07-22 19:19:38

#include
#include
#include
#include
#include
#include
#include
#include
#include
char file_ok[100]="HTTP/1.1 200 OK/r/nServer:Apche Tomcat/5.0.12\r\nContent-Type:text/html\r\n\r\n";
char file_not[100]="HTTP/.1 404 Not Found\r\nServer:Apache Tomcat/5.0.12/r/nContent-Type:text/html\r\nContent-Length:40\r\n\n";
char not_content[100]="file not found ";
int main(int argc,char *argv[])
{
 char recvbuf[1024]="\0";
 char client_dgram[1500];
 char client_path[40]="\0";
 char server_path[60]="\0";
 char server_path_temp[60]="\0";
 int server_sockfd,client_sockfd;
 struct sockaddr_in server_addr;
 struct sockaddr_in client_addr;
 unsigned short port=80;
 int client_len;
 char client_ip[INET_ADDRSTRLEN];
 char *token;
 int count=0;
 int fd_not_found,fd_ok,fd_html;
 
 if( argc>1 )
 {
  port=atoi(argv[1]);
 }
 printf("TCP Server Started at port %d!\n",port);
 server_sockfd = socket(AF_INET,SOCK_STREAM,0);
 if(server_sockfd<0)
 {
  perror("Invalid socket");
  exit(1);
 }
 bzero(&server_addr,sizeof(server_addr));
 server_addr.sin_family = AF_INET;
 server_addr.sin_port = htons(port);
 server_addr.sin_addr.s_addr = htonl(INADDR_ANY);
 printf("Binding server to port %d\n",port);
 if(bind(server_sockfd,(struct sockaddr *)&server_addr,sizeof(struct sockaddr))!=0)
 {
  close(server_sockfd);
  perror("binding err!");
  exit(1);
 }
 if(listen(server_sockfd,1)!=0)
 {
  close(server_sockfd);
  perror("listen err");
  exit(1);
 }
  printf("please input an absolute path:\n");
  scanf("%s",server_path);
  strcpy(server_path_temp,server_path);

 client_len=sizeof(client_addr);
 while(1)
 {
  count=0; 
  client_sockfd=accept(server_sockfd,(struct sockaddr *)&client_addr,&client_len);
  if(client_sockfd<0)
  {
   close(server_sockfd);
   perror("accept err!");
   exit(1);
  }
  inet_ntop(AF_INET,&client_addr.sin_addr.s_addr,client_ip,INET_ADDRSTRLEN);
  printf("the client ip = %s\n",client_ip);
  read(client_sockfd,client_dgram,1500);
  token=strtok(client_dgram," ");
  while(token!=NULL)
  {
   if(count==1)
   {
    strcpy(client_path,token);
    break;
   }
   token=strtok(NULL," ");
   count++;
  }
  strcat(server_path,client_path);
  fd_html=open(server_path,O_RDWR);
  if(access(server_path,F_OK)==0)
  {
   write(client_sockfd,file_ok,strlen(file_ok));
   while (read(fd_html,recvbuf,1024))
   {
    write(client_sockfd,recvbuf,1024);
   }
   close(client_sockfd);
  }
  else
  {
   write(client_sockfd,file_not,100);
   close(client_sockfd);
  }
  memset(recvbuf,0,1024);
  memset( client_dgram,0,1500);
  memset(client_path,0,40);
  memset(server_path,0,60);
  strcpy(server_path,server_path_temp);
  close(client_sockfd);
  
 }
}
 
 
简单写个基于http的webserver
阅读(438) | 评论(0) | 转发(0) |
0

上一篇:我的qt啊

下一篇:tftp client

给主人留下些什么吧!~~