Linux C语言Http POST上传图片

2019-07-13 08:37发布

最近需要在嵌入式设备写个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 ! "); cfd = socket(AF_INET, SOCK_STREAM, 0); if(-1 == cfd) { printf("socket fail ! "); return -1; } printf("socket ok ! "); 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 : %#x ",s_add.sin_addr.s_addr,s_add.sin_port); if(-1 == connect(cfd,(struct sockaddr *)(&s_add), sizeof(struct sockaddr))) { printf("connect fail ! "); return -1; } printf("connect ok ! "); unsigned long filesize = get_file_size("snap.jpg"); char header[1024]; sprintf(header, "POST /postpic.php HTTP/1.1 Content-Type: application/octet-stream User-Agent: cctv.mtv Host: 127.0.0.1 Content-Length: %ld Cache-Control: no-cache ", filesize); printf("%s ", header); unsigned long totalsize = strlen(header) + filesize; char* request = (char*)malloc(totalsize); if (request == NULL){ printf("malloc request fail ! "); return -1; } request[0] = '