473,395 Members | 1,624 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,395 software developers and data experts.

How to Receive Image Bytes From HTTP Response Through C Socket Programming?

Hi,

What command/technique is needed in a C program to receive image bytes through socket programming from an HTTP response? I want to develop a program that requests for an image from a server, then upon receiving the bytes comprising the image, it should write these bytes into a newly created file such that an image file is created. The image is of .jpg format. I really don't know how to create a program that receives and stores bytes through sockets so I hope someone here knows how to do it. So far, what I know is how to receive arrays of characters (strings) but now I want to know how to receive image bytes.

Also, the response my program is receiving has an HTTP header that comes before the actual image bytes so I need to remove the HTTP header first before writing the image bytes into a file. How do I do it? Thanks in advance. I'm working on a Windows XP machine.

The following is a code snippet of my program (so far, this is not yet able to create a .jpg image)

Expand|Select|Wrap|Line Numbers
  1.   char recvbuf[MAXBUFLEN];
  2.   FILE *fpic;
  3.  
  4.   fpic = fopen("picture.jpg", "w");
  5.   if (!fpic) {
  6.     printf("Error writing file\n");
  7.     return 1;
  8.   }
  9.  
  10.   numbytes=recv(ConnectSocket,recvbuf,sizeof(recvbuf),0);
  11.   if (numbytes == SOCKET_ERROR)
  12.      printf("Server: recv() error %ld.\n", WSAGetLastError());
  13.  
  14.   else {
  15.        printf("Server: Received data is: \"%s\"\n", recvbuf);
  16.        printf("Server: Bytes received: %ld.\n", numbytes);
  17.        fwrite(recvbuf, 1, strlen(recvbuf), fpic);
  18.        fclose(fpic);
  19.   }
  20.  
Mar 6 '11 #1
5 12040
Banfa
9,065 Expert Mod 8TB
I am guessing that you are expecting recv to return the entire entire HTTP packet containing the image in the 1 call. However that is not how TCP sockets work, if the socket has received data then when you call recv you can at best guarantee that you will receive 1 byte and for large images it is likely that you will need to call recv multiple times.

I suggest you get hold of and read Beej's Guide to Network Programming.

HTTP is a fairly simple protocol when returning an image it just sends its header and then takes the image data onto the end of the message (in binary) you just have to read the data off and store it.

HTTP uses caridge return as a separator. So for example you can attach to this site (using a telnet program) and request the main site image and what you get returned is

Expand|Select|Wrap|Line Numbers
  1. HTTP/1.1 200 OK
  2. Date: Mon, 07 Mar 2011 12:58:39 GMT
  3. Server: LiteSpeed
  4. Accept-Ranges: bytes
  5. Connection: Keep-Alive
  6. Keep-Alive: timeout=5, max=100
  7. Last-Modified: Wed, 06 Oct 2010 09:38:11 GMT
  8. Content-Type: image/gif
  9. Content-Length: 744
  10. Cache-Control: max-age=2592000
  11. Expires: Wed, 06 Apr 2011 12:58:39 GMT
  12.  
  13. GIF89ax▲─???▀Ù㻽½½{{KKK*╣8ÀÊ~╠╠╠þþþfffÖÖÖfff▄▄▄¶¶¶WWW───ç┤)¤ß¬»═qþ*ıÃ▄øƒ├SÀÀÀççç┐Îì!¨♦,x▲!Ädi×h¬«lÙ¥p,¤tm▀x«´|´áPà©Å╚d)
  14. ☺h:ƒÉ├!z@×Ûëüep▒Ó«!LNî▲â┼ò╠0]♦*©|¥$â↨♥¾╣8ÝØ►_v`mäXf♠çm%osÆquìM}♠âMÅ$
  15.                                                                     êÖûOåíf
  16.                                                                            îì£#æôÆòí♠VXZ"ÜÄÁíNúûf↓í®"½¼r«Më©O↓"ù#Xü"
  17.  
  18. ÈÈ♥X↓ıÈ
  19.        c╔┌▀yºù▀ı▄ÞÞ↨ÚýÞ¶t$╠Ã"XÿáO♥"×O¶┼À&─¿└ÆG┼£)☻└¤▼▬☻gÍ4)á└▬░↨╗ÚRíÇÓèâ        ↨.¹4┬▬,å÷─êûB^Fü)áaÓå☻$
  20.                                                                                                        à─ÔÕ║WÆÉ?.O@[@┤(Ð
  21. ♦┬@ └└ƒ═8)Ú┤─á  Ya2b¶Ju$í☻↓h>5§╬?;
  22.                                   ~Û    ├│%L↕┐F`hT éü▒%╩
  23. Ïuä☻__§Ó%í¸▀▒T▬░zµ¡è┴%░ò█fÔA♦♠³└dX<ó±T'■õ¨à+╩fͦ♦☻iªQ÷#∟;sk┴ûÙ²ªüÏ╔∟
  24.                                                                     ☺Æ+WnAõ┌¦Wâk▄õZ║¶↨Âåi↨0┴±_Ù├W╝▲q¢à☻┌
  25.                                                                                                         Â│Û■/â↨/┤øðéM↔xx
  26. PîÛçÑ▀hÿÐÛ╔!A~õ☻@[°§&▲ex]↓¿XÇp
  27. 6▓Ç]+h►çä)T¶ÌìMQË☻ÄjØ`Ò{jß(õìfêé<äÓüBy[±å╩tç└ÆDHÓäû,░Üå▒0×p
  28.                               9Ç6ö® ú4ßõô%╚Ï$öT:®┴öUfi;
  29.  
You get the headers, which give the content type and length, each header ends in a CR and then there is an additional CR at the end of the headers giving a blank line and then the image content (binary GIF data).
Mar 7 '11 #2
So, what do I have to do now? How do I remove the header? Should I try to find the \r\n\r\n part? Also, how do I know if I have already received all the data that the server had sent to me? Thanks
Mar 7 '11 #3
Banfa
9,065 Expert Mod 8TB
You read the headers by simply reading the data line by line. You look for the start of content (the \r\n\r\n) and you know how long the content is because it is in the content-length header that you will already have parsed.

You will have to accept that you are going to start receiving data without knowing how much data you are finally going to receive but that you will know how much data you are receiving before you have finished receiving it.
Mar 7 '11 #4
>you know how long the content is because it is in the content-length header that you will already have parsed

I know the content length of the data, but how will my program know it from the header? Do I have to create a function that will find the "Content-Length" part of the header?
Mar 8 '11 #5
Banfa
9,065 Expert Mod 8TB
At the very least you should write code that parses the "Content-Length" header. It should be too hard as all you need to do is look for "Content-Length" at the start of any header line. It may be worth looking for the "Content-Type" header too just to verify what you are downloading, you can probably ignore the rest of the headers.

The content length header is well defined so once you have located it and skipped passed the ":" a quick call to atoi should get you the length.
Mar 8 '11 #6

Sign in to post your reply or Sign up for a free account.

Similar topics

1
by: exquisitus | last post by:
Hi all, I'm writing a C socket application that uses either TCP/IP or UDP/IP (specified at command line). I want to be able to send the data that I receive to a HTTP server. Is there an HTTP...
6
by: Paul Fi | last post by:
i have little knowledge of socket programming, but what i know is that using sockets we exchange text between endpoints of the socket but first we convert the text to array of bytes and we send it...
5
by: John Sheppard | last post by:
Hi all, I am not sure that I am posting this in the right group but here it goes anyway. I am new to socket programming and I have been searching on the internet to the questions I am about to pose...
1
by: John Sheppard | last post by:
Thanks to everyone that responded to my previous Socket Programming question. Now I have run into some behavior that I don't quite understand. Programming environment. VS.NET 2003, C#, Windows...
5
by: kuba bogaczewicz | last post by:
Hello all, for my school project I have to write a small peer-2-peer application using Sockets, and I've chosen C# for the task. I've been doing some research on the topic, and I would really...
2
by: | last post by:
Hello All, I am writing a web application that reads a bitmap from a file and outputing it to a HTTP response stream to return the image to the requesting client. The image file is a regular...
1
by: Sean | last post by:
Hi, I am trying to write a simple chat/text messaging program but I am having some problems. I am a rookie when it comes to socket programming so I am not sure if I am doing the write thing or...
9
by: Hao | last post by:
We are doing very intensive network communication. We collect data from thousands of electric devices every minutes. The devices understand both socket and web service. They are either embeded...
8
by: =?Utf-8?B?Sm9obg==?= | last post by:
Hi all, I am new to .net technologies. ASP.NET supports socket programming like send/receive in c or c++? I am developing web-site application in asp.net and code behind is Visual C#. In...
3
by: Praveen Raj V | last post by:
"socket.Available" is not working. How would you Determine number of bytes present in a TCP/IP socket before reading those bytes without using socket.Available void Receive(Socket socket, byte...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.