最近需要在嵌入式设备写个POST图片的功能,但是找了很久都没有现成的代码,curl放入嵌入式设备又太臃肿,现在分享一下代码
#include
#include
#include
#include
#include
#include
#include
unsigned long get_file_size(const char *path)
{
unsigned long filesize = -1;
struct stat statbuff;
if(stat(path, &statbuff) < 0){
return filesize;
}else{
filesize = statbuff.st_size;
}
return filesize;
}
int main()
{
int cfd;
int recbytes;
int sin_size;
char buffer[1024]={0};
struct sockaddr_in s_add,c_add;
unsigned short portnum=80;
printf("Hello,welcome to client !rn");
cfd = socket(AF_INET, SOCK_STREAM, 0);
if(-1 == cfd)
{
printf("socket fail ! rn");
return -1;
}
printf("socket ok !rn");
bzero(&s_add,sizeof(struct sockaddr_in));
s_add.sin_family=AF_INET;
s_add.sin_addr.s_addr= inet_addr("127.0.0.1");
s_add.sin_port=htons(portnum);
printf("s_addr = %#x ,port : %#xrn",s_add.sin_addr.s_addr,s_add.sin_port);
if(-1 == connect(cfd,(struct sockaddr *)(&s_add), sizeof(struct sockaddr)))
{
printf("connect fail !rn");
return -1;
}
printf("connect ok !rn");
unsigned long filesize = get_file_size("snap.jpg");
char header[1024];
sprintf(header, "POST /postpic.php HTTP/1.1rnContent-Type: application/octet-streamrnUser-Agent: cctv.mtvrnHost: 127.0.0.1rnContent-Length: %ldrnCache-Control: no-cachernrn", filesize);
printf("%srn", header);
unsigned long totalsize = strlen(header) + filesize;
char* request = (char*)malloc(totalsize);
if (request == NULL){
printf("malloc request fail !rn");
return -1;
}
request[0] = '';
strcat(request, header);
FILE* fp = fopen("snap.jpg", "rb+");
if (fp == NULL){
printf("open file fail!rn");
return -1;
}
int readbyte = fread(request+strlen(request), 1, filesize, fp);
printf("fread return: %dn", readbyte);
if(-1 == write(cfd,request,totalsize))
{
printf("write fail!rn");
return -1;
}
printf("write ok!rn");
if(-1 == (recbytes = read(cfd,buffer,1024)))
{
printf("read data fail !rn");
return -1;
}
printf("read okrnREC:rn");
buffer[recbytes]='';
printf("%srn",buffer);
free(request);
fclose(fp);
close(cfd);
return 0;
}
最后
以上就是优雅短靴最近收集整理的关于linux c post上传文件,Linux C语言Http POST上传图片的全部内容,更多相关linux内容请搜索靠谱客的其他文章。
发表评论 取消回复