⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 file_send.c

📁 linux 网络编程 c C++ UDP tcp
💻 C
字号:
#include <stdio.h>#include <stdlib.h>#include <errno.h>#include <string.h>#include <netdb.h>#include <sys/types.h>#include <netinet/in.h>#include <sys/socket.h>#include <unistd.h>#include <fcntl.h>#define MAX_BUF_SIZE    1024#define SERVPORT 	6666struct context{	int flag;	/*					1: file name ,				   	2: file data  ,				   	3: file end   ,				   	other: error				 */	int counts;	char data[1024];};int main(int argc,char *argv[]){// #file_send 192.168.0.1 ttst.mp3	int sockfd,n,sendbytes,sendpkgs=0;		int sendfilefd,read_count;	char buffer[MAX_BUF_SIZE];	char filename[50];	struct hostent *host;	struct sockaddr_in serv_addr;	struct context sendcontext;		bzero((char *)&sendcontext,sizeof(struct context));	if(argc != 3)	{		fprintf(stderr,"Please enter the server's hostname!\n");		exit(1);	}		if((host=gethostbyname(argv[1]))==NULL)	{		perror("gethostbyname");		exit(1);	}		if((sockfd=socket(AF_INET,SOCK_STREAM,0))==-1)	{		perror("socket");		exit(1);	}		serv_addr.sin_family=AF_INET;	serv_addr.sin_port=htons(SERVPORT);	serv_addr.sin_addr=*((struct in_addr *)host->h_addr);	bzero((char *)&(serv_addr.sin_zero),8);	if(connect(sockfd,(struct sockaddr *)&serv_addr,\		sizeof(struct sockaddr))==-1)	{		perror("connect");		exit(1);	}	if((sendfilefd = open(argv[2],O_RDONLY)) < 0)	 		{		fprintf(stderr,"Usage: the file:%s is not exist  \n",argv[2]);		close(sockfd);		exit(1);	}    else 	{      strcpy(filename,argv[2]);      printf("open sendfile:%s: fd %d is OK! ....\n",filename,sendfilefd);	}		bzero((char *)&sendcontext,sizeof(struct context));	sendcontext.flag = 1;	n=strlen(filename);	strcpy(sendcontext.data,filename);		sendcontext.data[n]='\0';	if((sendbytes=send(sockfd,&sendcontext,sizeof(struct context),0))==-1)	{		perror("send");		exit(1);	}		while(1)	{		if ((read_count=read(sendfilefd,buffer,1024)) < 0)	    {		    printf("read file is error ....\n");			exit(-1);		    break;     	    }		else if(read_count > 0)		{			sendcontext.flag = 2;			strcpy(sendcontext.data, buffer);			sendcontext.counts = read_count;			if((sendbytes=send(sockfd,&sendcontext,sizeof(struct context),0))==-1)			{				perror("send");				exit(1);			}			printf("you have send %d packages , %d chars....\n",++sendpkgs,read_count);					}		else		{//			bzero((char *)&sendcontext,sizeof(struct context));			sendcontext.flag = 3;			sendcontext.counts = 0;			if((sendbytes=send(sockfd,&sendcontext,read_count+1,0))==-1)			{				perror("send");				exit(1);			}			close(sendfilefd);			close(sockfd);			return 0;		}	}	}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -