TCP之client.c和common.h

</pre><p>client.c </p><pre class="cpp" name="code">#include "../Common/common.h"
  
int main(int argc, char *argv[])  
{  
    int clientfd;  
  
    if(argc!=2)  
    {  
        fprintf(stderr,"Usage:./fileclient <IP_Address>\n");  
        exit(1);  
    }  
    struct sockaddr_in clientaddr;  
    bzero(&clientaddr,sizeof(clientaddr));    
  
    clientaddr.sin_family=AF_INET;  
    clientaddr.sin_addr.s_addr=htons(INADDR_ANY);  
    clientaddr.sin_port=htons(0);  
      
    clientfd=socket(AF_INET,SOCK_STREAM,0);  
      
    if(clientfd<0)     
    {  
        perror("socket");  
        exit(1);  
    }  
  
    if(bind(clientfd,(struct sockaddr*)&clientaddr,sizeof(clientaddr))<0)  
    {  
        perror("bind");  
        exit(1);  
    }  
  
    struct sockaddr_in svraddr;  
    bzero(&svraddr,sizeof(svraddr));  
	//将字符串形式的IP地址转换成网络字节序
    if(inet_aton(argv[1],&svraddr.sin_addr)==0)  
    {  
        perror("inet_aton");  
        exit(1);  
    }  
    svraddr.sin_family=AF_INET;  
    svraddr.sin_port=htons(PORT);  
      
    socklen_t svraddrlen=sizeof(svraddr);  
    if(connect(clientfd,(struct sockaddr*)&svraddr,svraddrlen)<0)      
    {  
        perror("connect");  
        exit(1);  
    }  
      
    //recv file imformation  
    char buff[BUFFSIZE];  
    char filename[FILE_NAME_MAX_SIZE];  
    int count;  
    bzero(buff,BUFFSIZE);  
  
    count=recv(clientfd,buff,BUFFSIZE,0);  
    if(count<0)  
    {  
        perror("recv");  
        exit(1);  
    }  
    strncpy(filename,buff,strlen(buff)>FILE_NAME_MAX_SIZE?FILE_NAME_MAX_SIZE:strlen(buff));  
  
    printf("Preparing recv file : %s from %s \n",filename,argv[1]);   
  
    //recv file  
    FILE *fd=fopen(filename,"wb+");  
    if(NULL==fd)  
    {  
        perror("open");  
        exit(1);  
    }  
    bzero(buff,BUFFSIZE);  
  
    int length=0;  
    while(length=recv(clientfd,buff,BUFFSIZE,0))  
    {  
        if(length<0)  
        {  
            perror("recv");  
            exit(1);  
        }  
        int writelen=fwrite(buff,sizeof(char),length,fd);  
        if(writelen<length)  
        {  
            perror("write");  
            exit(1);  
        }  
        bzero(buff,BUFFSIZE);  
    }  
    printf("Receieved file:%s from %s finished!\n",filename,argv[1]);  
    fclose(fd);  
    close(clientfd);  
    return 0;  
}  

 

 

common.h

#ifndef __COMMON_H_
#define __COMMON_H_

#include <stdio.h>  
#include <stdlib.h>  
#include <unistd.h>  
#include <string.h>  
#include <sys/types.h>  
#include <sys/stat.h>  
#include <sys/socket.h>  
#include <netinet/in.h>  
  
#define PORT 6000  
#define LISTENQ 20  
#define BUFFSIZE 4096  
#define FILE_NAME_MAX_SIZE 512

#endif


 


 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值