Chinaunix首页 | 论坛 | 博客
  • 博客访问: 42645
  • 博文数量: 20
  • 博客积分: 475
  • 博客等级: 下士
  • 技术积分: 215
  • 用 户 组: 普通用户
  • 注册时间: 2011-03-04 21:13
文章分类

全部博文(20)

文章存档

2011年(20)

我的朋友
最近访客

分类: C/C++

2011-08-25 20:13:21

  1. /*
  2. *服务器端,发送命令,等待结果回传
  3. * By rekken
  4. */
  5. #include <sys/types.h>
  6. #include <stdlib.h>
  7. #include <stdio.h>
  8. #include <errno.h>
  9. #include <netinet/in.h>
  10. #include <sys/socket.h>
  11. #include <string.h>
  12. #include <netdb.h>
  13. #define SERVERPORT 3490
  14. int main(int argc,char *argv[])
  15. {
  16.         //scokfd:a socket descriptor, sendbytes and recvbytes used for send() and recv(),
  17.     int sockfd,sendbytes,recvbytes;
  18.     char recvdata[65535];        //store the data received
  19.     char i_return[65535];
  20.     char *p_return;
  21.     char *i_Command=argv[2];    //argv[2] store the file dir received from the keyboard
  22.     struct hostent *host;    //for dns transmition
  23.     struct sockaddr_in serv_addr;    //store the ip and other server info
  24.     if(argc<3){
  25.         fprintf(stderr,"Please enter AS: servername fileDirectory\n");
  26.         exit(1);
  27.     }
  28.         //address resolution function
  29.     if((host=gethostbyname(argv[1]))==NULL){
  30.         perror("gethostbyname");
  31.         exit(1);
  32.     }
  33.         //file directory not NULL
  34.     if(i_Command==NULL){
  35.         perror("file");
  36.         exit(1);
  37.     }
  38.         //create socket
  39.     if((sockfd=socket(AF_INET,SOCK_STREAM,0))==-1){
  40.         perror("socket");
  41.         exit(1);
  42.     }
  43.         //set relevant parameters in the socketr_in struct
  44.     serv_addr.sin_family=AF_INET;
  45.     serv_addr.sin_port=htons(SERVERPORT);
  46.     serv_addr.sin_addr=*((struct in_addr *)host->h_addr);
  47.     bzero(&(serv_addr.sin_zero),8);
  48.         //call the connect() function to connect to server intiative
  49.     if(connect(sockfd,(struct sockaddr *)&serv_addr,sizeof(struct sockaddr))==-1){
  50.         perror("connect");
  51.         exit(1);
  52.     }
  53.         //send message to sever
  54.     if((sendbytes=send(sockfd,i_Command,120,0))==-1){
  55.         perror("send");
  56.         exit(1);
  57.     }
  58.     printf("Send:%s\n",argv[2]);
  59.         //receive data
  60.         p_return=i_return;
  61.      while(1){
  62.         if((recvbytes=recv(sockfd,recvdata,65535,0))==-1){
  63.             perror("receive file:");
  64.             exit(1);
  65.         }
  66.         memcpy(p_return,recvdata,recvbytes);
  67.         p_return=p_return+recvbytes;
  68.         if(!recvbytes)
  69.             break;
  70.     };
  71.             printf("Receive data :%s",i_return);
  72.     close(sockfd);
  73.     return 1;
  74. }
阅读(797) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~