Linux socket send file

来源:互联网 发布:web即时通讯源码 编辑:程序博客网 时间:2024/05/29 18:04
/******************************send file*******************************#include <sys/types.h>          #include <sys/socket.h>#include <strings.h>#include <string.h>#include <errno.h>#include <stdio.h>#include <stdlib.h>#include <netinet/in.h>#include <arpa/inet.h>#include <unistd.h>#include <sys/stat.h>#include <fcntl.h>#define MAXLEN 1024struct file_info{int size;char name[32];};struct file_info parse_file(int fd, char *str){char *ptr = NULL;struct stat f_stat;struct file_info info;fstat(fd , &f_stat);if(S_ISDIR(f_stat.st_mode)){printf("not support dir\n");close(fd);exit(1);}ptr = strrchr(str, '/');printf("size = %d\n", f_stat.st_size);info.size = f_stat.st_size;strcpy(info.name , ++ptr);//printf("info.name = %s \n", info.name);return info;}void usage(void){printf("command   <file_name>\n");exit(-1);}int main(int argc, char *argv[]){int cli_fd = -1;int file_fd = -1;int num = -1;int ret = -1;char buf[MAXLEN];struct file_info node;struct sockaddr_in  srv_addr;  if(argc != 2 )usage();file_fd = open(argv[1], O_RDONLY);if(file_fd < 0){perror("open");exit(1);}node = parse_file(file_fd, argv[1]);printf("node.name = %s\n", node.name);printf("node.size = %d\n", node.size);cli_fd = socket( AF_INET, SOCK_STREAM,  0);if(cli_fd < 0){perror("socket");exit(1);}bzero(&srv_addr, sizeof(srv_addr));srv_addr.sin_family = AF_INET;srv_addr.sin_port =  htons(7890);srv_addr.sin_addr.s_addr = inet_addr("192.168.7.11");  ret = connect(cli_fd,  (struct sockaddr *)&srv_addr,   sizeof(srv_addr));if(ret < 0){perror("connect");exit(1);}node.size = htonl(node.size);num = write(cli_fd, &node , sizeof(node));printf("start tranfer .....\n");int total = 0;while(1){num = read(file_fd, buf, MAXLEN);if(num == 0)break;write(cli_fd, buf,  num);total += num;}printf("tranfer total %d done\n", total);close(file_fd);close(cli_fd);return 0;}