1 | /* |
---|
2 | * Copyright (c) 2012 embedded brains GmbH. All rights reserved. |
---|
3 | * |
---|
4 | * embedded brains GmbH |
---|
5 | * Obere Lagerstr. 30 |
---|
6 | * 82178 Puchheim |
---|
7 | * Germany |
---|
8 | * <rtems@embedded-brains.de> |
---|
9 | * |
---|
10 | * The license and distribution terms for this file may be |
---|
11 | * found in the file LICENSE in this distribution or at |
---|
12 | * http://www.rtems.com/license/LICENSE. |
---|
13 | */ |
---|
14 | |
---|
15 | |
---|
16 | #include <sys/types.h> |
---|
17 | #include <sys/socket.h> |
---|
18 | #include <netinet/in.h> |
---|
19 | #include <netinet/tcp.h> |
---|
20 | #include <netdb.h> |
---|
21 | #include <unistd.h> |
---|
22 | |
---|
23 | #include "test-http-client.h" |
---|
24 | |
---|
25 | void httpc_init_context( |
---|
26 | httpc_context *ctx |
---|
27 | ) |
---|
28 | { |
---|
29 | ctx->socket = -1; |
---|
30 | ctx->fd = NULL; |
---|
31 | } |
---|
32 | |
---|
33 | bool httpc_open_connection( |
---|
34 | httpc_context *ctx, |
---|
35 | char *targethost, |
---|
36 | int targetport |
---|
37 | ) |
---|
38 | { |
---|
39 | struct sockaddr_in addr; |
---|
40 | |
---|
41 | struct hostent *server; |
---|
42 | |
---|
43 | ctx->socket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); |
---|
44 | if(ctx->socket < 0) { return false; } |
---|
45 | |
---|
46 | memset(&addr, 0, sizeof(addr)); |
---|
47 | addr.sin_family = AF_INET; |
---|
48 | addr.sin_port = htons(targetport); |
---|
49 | |
---|
50 | server = gethostbyname(targethost); |
---|
51 | if(server == NULL) { return false; } |
---|
52 | memcpy(&addr.sin_addr.s_addr, server->h_addr, (size_t) server->h_length); |
---|
53 | |
---|
54 | if(connect(ctx->socket, (struct sockaddr *)&addr, sizeof(addr)) != 0) |
---|
55 | { |
---|
56 | return false; |
---|
57 | } |
---|
58 | |
---|
59 | ctx->fd = fdopen(ctx->socket,"rw"); |
---|
60 | if(ctx->fd == NULL) { return false; } |
---|
61 | |
---|
62 | return true; |
---|
63 | } |
---|
64 | |
---|
65 | bool httpc_close_connection( |
---|
66 | httpc_context *ctx |
---|
67 | ) |
---|
68 | { |
---|
69 | if(close(ctx->socket) != 0) |
---|
70 | { |
---|
71 | return false; |
---|
72 | } |
---|
73 | |
---|
74 | return true; |
---|
75 | } |
---|
76 | |
---|
77 | bool httpc_send_request( |
---|
78 | httpc_context *ctx, |
---|
79 | char *request, |
---|
80 | char *response, |
---|
81 | int responsesize |
---|
82 | ) |
---|
83 | { |
---|
84 | int size = strlen(request); |
---|
85 | char lineend[] = " HTTP/1.1\r\n\r\n"; |
---|
86 | |
---|
87 | write(ctx->socket, request, size); |
---|
88 | write(ctx->socket, lineend, sizeof(lineend)); |
---|
89 | |
---|
90 | size = read(ctx->socket, response, responsesize-1); |
---|
91 | response[size] = '\0'; |
---|
92 | |
---|
93 | return true; |
---|
94 | } |
---|
95 | |
---|