I want to write a C program to generate a Get Request without using any external libraries. Is this possible using only C libraries, using sockets ? I'm thinking of crafting a http packet(using proper formatting) and sending it to the server. Is this the only possible way or is there a better way ?
相关问题
- Angular RxJS mergeMap types
- Multiple sockets for clients to connect to
- What is the best way to do a search in a large fil
- Google Apps Script: testing doPost() with cURL
- How to instantiate Http service in main.ts manuall
POSIX 7 minimal runnable example
Let's fetch http://example.com.
wget.c
GitHub upstream.
Compile:
Get http://example.com and output to stdout:
This command hangs for most servers until timeout, and that is expected:
Content-Length
is not sent, the server can just close to determine length.The connection part also works with the IP:
gives:
and so we do:
however, the reply is an error, because we are not setting the
Host:
properly in our program, and that is required in HTTP 1.1.A server example can be found: Send and Receive a file in socket programming in Linux with C/C++ (GCC/G++)
Tested on Ubuntu 18.04.
“Without any external libraries” strictly speaking would exclude libc as well, so you'd have to write all syscalls yourself. I doubt you mean it that strict, though. If you don't want to link to another library, and don't want to copy source code from another library into your application, then directly dealing with the TCP stream using the socket API is your best approach.
Creating the HTTP request and sending it over a TCP socket connection is easy, as is reading the answer. It's parsing the answer which is going to be real tricky, particularly if you aim to support a reasonably large portion of the standard. Things like error pages, redirects, content negotiation and so on can make our life quite hard if you're talking to arbitrary web servers. If on the other hand the server is known to be well-behaved, and a simple error message is all right for any unexpected server response, then that is reasonably simple as well.
Using BSD sockets or, if you're somewhat limited, say you have some RTOS, some simpler TCP stack, like lwIP, you can form the GET/POST request.
There are a number of open-source implementations. See the "happyhttp" as a sample ( http://scumways.com/happyhttp/happyhttp.html ). I know, it is C++, not C, but the only thing that is "C++-dependant" there is a string/array management, so it is easily ported to pure C.
Beware, there are no "packets", since HTTP is usually transfered over the TCP connection, so technically there is only a stream of symbols in RFC format. Since http requests are usually done in a connect-send-disconnect manner, one might actually call this a "packet".
Basically, once you have an open socket (sockfd) "all" you have to do is something like