C string interpolation
I'm building simple http status checker in C. I've got the network part done, but I'm having trouble with string manipulation. Here how it works:
$ ./client http://domain.com/path.html#anchor
200
This utility simply outputs the status of given page on the command line. I need to parse the given string into hostname and request path. I've also built a "template" string with this define:
#define HTTP_GET_M开发者_StackOverflowSG "GET %s HTTP/1.1\nUser-Agent: my-agent-0.01\nHost: %s\n\n"
I'd like to know how should I approach the interpolation of parsed url (host and path) into this defined string before send()
ing it to the socket?
A simple approach is to use sprintf:
char req[ SOME_SUITABLE_SIZE ];
sprintf( req, HTTP_GET_MSG, host, path );
but this will be vunerable to buffer overruns unless you check the lengths of "host" and "path" beforehand. If your system has snprintf you can avoid this:
snprintf( req, SOME_SUITABLE_SIZE, HTTP_GET_MSG, host, path );
精彩评论