From c09bd7a16b56deedaef8d74ba736fc042bb4fcac Mon Sep 17 00:00:00 2001 From: Paul Sokolovsky Date: Mon, 5 Feb 2018 16:05:11 +0200 Subject: [PATCH] samples: sockets: http_get: More configurability and logging Make it easy to override HTTP host/port/path. Print URL which we request and make few other adjustment to the output for clarity. Signed-off-by: Paul Sokolovsky --- samples/net/sockets/http_get/src/http_get.c | 25 ++++++++++++++++----- 1 file changed, 19 insertions(+), 6 deletions(-) diff --git a/samples/net/sockets/http_get/src/http_get.c b/samples/net/sockets/http_get/src/http_get.c index 40bc4b27c5ef..88f1e398e614 100644 --- a/samples/net/sockets/http_get/src/http_get.c +++ b/samples/net/sockets/http_get/src/http_get.c @@ -22,17 +22,25 @@ #endif +/* HTTP server to connect to */ +#define HTTP_HOST "google.com" +/* Port to connect to, as string */ +#define HTTP_PORT "80" +/* HTTP path to request */ +#define HTTP_PATH "/" + + #define SSTRLEN(s) (sizeof(s) - 1) #define CHECK(r) { if (r == -1) { printf("Error: " #r "\n"); } } -#define REQUEST "GET / HTTP/1.0\r\n\r\n" +#define REQUEST "GET " HTTP_PATH " HTTP/1.0\r\n\r\n" static char response[1024]; void dump_addrinfo(const struct addrinfo *ai) { - printf("addrinfo @%p: fam=%d, socktype=%d, proto=%d, " - "addr_fam=%d, addr_port=%x\n", + printf("addrinfo @%p: ai_family=%d, ai_socktype=%d, ai_protocol=%d, " + "sa_family=%d, sin_port=%x\n", ai, ai->ai_family, ai->ai_socktype, ai->ai_protocol, ai->ai_addr->sa_family, ((struct sockaddr_in *)ai->ai_addr)->sin_port); @@ -44,9 +52,12 @@ int main(void) struct addrinfo *res; int st, sock; + printf("Preparing HTTP GET request for http://" HTTP_HOST + ":" HTTP_PORT HTTP_PATH "\n"); + hints.ai_family = AF_INET; hints.ai_socktype = SOCK_STREAM; - st = getaddrinfo("google.com", "80", &hints, &res); + st = getaddrinfo(HTTP_HOST, HTTP_PORT, &hints, &res); printf("getaddrinfo status: %d\n", st); if (st != 0) { @@ -68,7 +79,7 @@ int main(void) CHECK(connect(sock, res->ai_addr, res->ai_addrlen)); send(sock, REQUEST, SSTRLEN(REQUEST), 0); - printf("Response:\n"); + printf("Response:\n\n"); while (1) { int len = recv(sock, response, sizeof(response) - 1, 0); @@ -83,8 +94,10 @@ int main(void) } response[len] = 0; - printf("%s", response); + printf("%s\n", response); } + close(sock); + return 0; }