函数定义:
char* httpdown(char *domain, int port, char *uri, int *length) ;
调用:
strcpy(uri, "/net.php");
rtn = httpdown("192.168.1.24", 80, uri, &len);
printf("File saved %s ", rtn);
大概发现printf这句会报那个错,如果uri是个txt或者jpg都不会报 。
经过一番折腾后发现是memcpy的问题,改成strncpy就可以了,但那样如果是图片又不能正确处理,所以,就只好判断下返回数据类型了,具体代码:
char* httpdown(char *domain, int port, char *uri, int *length) { char buffer[RECEIVE_BUF + 1]; //memset(buffer, ' ', RECEIVE_BUF + 1); char* rtn; rtn = malloc(DOWNLOAD_BUF); rtn[0] = 0; (*length) = 0; int sockfd = openRequest(domain, port, uri, rtn, buffer); #ifdef DEBUG if (sockfd < 0){ printf("Connect to %s:%d failed ", domain, port); return rtn; } #else if (sockfd < 0) return rtn; #endif #ifdef DEBUG printf("Init connect to %s:%d done, fd=%d ", domain, port, sockfd); #endif int len, needLen, dataLen=0; int current_buffer_size = DOWNLOAD_BUF; rtn[0] = 0; buffer[0] = 0; int type = -1; char * tmp; while (1) { len = recv(sockfd, buffer, RECEIVE_BUF, 0); if(type<0){//如果没有取得返回数据类型 tmp = strstr(buffer, "Content-Type");//如果已经获得content-type——潜在bug如果content-type和他的值没有一起返回则会出问题,不管了 if(tmp!=NULL){ tmp = strstr(tmp, "text"); if(tmp==NULL) type=1; else type=0; } } if (len > 0) { needLen = dataLen + len; while (current_buffer_size <= needLen) { current_buffer_size += DOWNLOAD_BUF; #ifdef DEBUG printf("realloc to %d ", current_buffer_size); #endif rtn = realloc(rtn, current_buffer_size); rtn[dataLen] = 0; } #ifdef DEBUG printf("http sockect received %d data ", len); #endif if(type<1)//字符串用strncat strncat(rtn+dataLen, buffer, len); else memcpy(rtn+dataLen, buffer, len); dataLen+=len; } else { if (len < 0) { if(errno>0) sprintf(rtn, "消息接收失败!错误代码是%d,错误信息是'%s' ", errno, strerror(errno)); return rtn; } #ifdef DEBUG printf("Read data from %s:%d, complete ", domain, port); #endif break; } } close(sockfd); (*length) = dataLen; return rtn; }