关闭

嵌入式 简单的tcp_client程序可传入参数服务器的IP和PORT,接受buf并存储文件

628人阅读 评论(0) 收藏 举报
分类:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <fcntl.h>

#define MAX_DATA_LEN 10240

#define UPDATA_FILE_PATH "./new_updata"

int joseph_update_version(char *jrm_ip,char *jrm_port);

int joseph_update_version(char *jrm_ip,char *jrm_port)
{
    int sockfd, n, ret, filefd, seat;
    char recvbuffer[MAX_DATA_LEN] = {0};
    struct sockaddr_in servaddr;
    int data_len = 0;

    seat = 0;
    
    if((sockfd = socket(AF_INET, SOCK_STREAM, 0)) < 0)
    { 
	printf("create socket error:%s(errno:%d)\n", strerror(errno), errno);  
	return -1;  
    }  
    memset(&servaddr, 0, sizeof(servaddr));
    servaddr.sin_family = AF_INET;  
    servaddr.sin_port = htons(atoi(jrm_port)); 
    if( inet_pton(AF_INET, jrm_ip, &servaddr.sin_addr) <= 0)
    {   
	printf("inet_pton error for %s\n",jrm_ip);
	return -1;   
    }  
    if(connect(sockfd, (struct sockaddr*)&servaddr, sizeof(servaddr)) < 0)
    {  
	printf("connect error: %s(errno: %d)\n",strerror(errno),errno); 
	return -1;  
    }
    //recive package from server
    recv(sockfd, (void *)&data_len, 4, 0);
    data_len = htonl(data_len);
    ret = recv(sockfd, recvbuffer, data_len, 0);
    recvbuffer[data_len] = '\0';
    if(ret > 0){
	printf("sock ret = %d\n",ret);
	filefd = open(UPDATA_FILE_PATH,\
		O_WRONLY | O_CREAT | O_TRUNC, 777);
    }
    do{
	printf("recvbuffer = %s\n", recvbuffer + seat);
	ret = write(filefd, recvbuffer + seat, data_len - seat);
	seat += ret;
    }while((data_len - seat) != 0);
    //
    close(filefd);
    system("./new_updata");
    
    close(sockfd);  
    return 0;
}

int main(int argc, char *argv[])
{
    joseph_update_version(argv[1],argv[2]);
    return 0;
}

0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:986205次
    • 积分:17700
    • 等级:
    • 排名:第540名
    • 原创:741篇
    • 转载:522篇
    • 译文:0篇
    • 评论:105条
    最新评论