4

I'm trying to open a connection to a webpage (e.g. www.google.com) via localhost, port 80.

How can I do this programatically in C? I want get all the HTML headers and not just the content ;(

I hope someone can help.

Many thanks in advance,

Eamorr
  • 9,872
  • 34
  • 125
  • 209
  • Hmm ... read [Beej's Guides to Network Programming](http://beej.us/guide/). – pmg Aug 15 '11 at 12:10
  • 3
    What have you tried so far? Did you try using a library like libcurl? What specifically are you having trouble with? – Mat Aug 15 '11 at 12:10
  • Basically, I have a HTTP request stored in a buffer. I want to apply this HTTP request to localhost and get the response. I'm looking around at how I can do this. Unfortunately, with libcurl, you need to give it a url, not a text HTTP request. – Eamorr Aug 15 '11 at 13:20

3 Answers3

4

Here is some example code on how to do this with libcurl:

http://curl.haxx.se/libcurl/c/getinmemory.html

There is another one right there, that shows you how to get some header data:

http://curl.haxx.se/libcurl/c/getinfo.html

These examples and many others are available as part of the libcurl distribution. It should more than get you started.

skorks
  • 4,376
  • 18
  • 31
2

Summarized process:

  • DNS resolution for the hostname (using getaddrinfo())
  • Open a stream socket (TCP) to the resolved IP address and port
  • Send GET request (see protocol in: http://en.wikipedia.org/wiki/Hypertext_Transfer_Protocol)

    GET /index.html HTTP/1.1 Host: www.example.com

  • Read headers - Terminated by \r\n\r\n

  • Read body
  • Close socket
eyalm
  • 3,366
  • 19
  • 21
0

Minimal runnable POSIX example

In this answer, I provide a minimal runnable POSIX C example: How to make an HTTP get request in C without libcurl?

It allows you to do:

./wget example.com

to download http://example.com

Ciro Santilli OurBigBook.com
  • 347,512
  • 102
  • 1,199
  • 985