Send binary file in HTTP response using C sockets

一曲冷凌霜 提交于 2019-11-28 10:17:10

The problem is that your message body is being treated as a null-terminated text string (you use strcat and strlen on it), when it isn't one: it is binary data (a PNG file). Therefore, strcat and strlen both stop on the first 0 byte in the image (typically quite early).

Your program is even printing out the response body: notice that it gives the correct header, but that once the PNG header (binary data) starts, there is only a few bytes.

  1. The line strcat(reply, buffer), where buffer potentially contains 0 bytes. Change it to memcpy(reply+strlen(header), buffer, fileLen).
  2. The line send(client, reply, strlen(reply), 0), where reply potentially contains 0 bytes. Pre-calculate the length of the reply, or replace the strlen with strlen(header)+fileLen.

Another bug is that you aren't closing the connection when you're done, so the browser will just wait forever. You need this, after send:

close(client);

The HTTP protocol specifies that it expects "\r\n" instead of "\n". Try that. :)

strcat(reply, buffer); // this is incorrect, because png(buffer) may contain zero byte
send(client, reply, strlen(reply), 0);
strlen(reply) // this is incorrect, because png may contain zero byte

I tried to follow what you did but could not get it to work. Instead, I found it easier to just send header and file separately.

e.g.

send(client, header, strlen(header), 0);
send(client, buffer, fileLen + 1, 0);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!