summaryrefslogtreecommitdiffstats
path: root/testsuites/libtests/mghttpd01/test-http-client.c
blob: 4902db46ab0933444b2b88825540f443a35364e0 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
/*
 * Copyright (c) 2012 embedded brains GmbH.  All rights reserved.
 *
 *  embedded brains GmbH
 *  Obere Lagerstr. 30
 *  82178 Puchheim
 *  Germany
 *  <rtems@embedded-brains.de>
 *
 * The license and distribution terms for this file may be
 * found in the file LICENSE in this distribution or at
 * http://www.rtems.org/license/LICENSE.
 */


#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netinet/tcp.h>
#include <netdb.h>
#include <unistd.h>
#include <string.h>

#include "test-http-client.h"

void httpc_init_context(
  httpc_context *ctx
)
{
  ctx->socket = -1;
  ctx->fd = NULL;
}

bool httpc_open_connection(
  httpc_context *ctx,
  char *targethost,
  int targetport
)
{
  struct sockaddr_in addr;

  struct hostent *server;

  ctx->socket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
  if(ctx->socket < 0) { return false; }

  memset(&addr, 0, sizeof(addr));
  addr.sin_family = AF_INET;
  addr.sin_port = htons(targetport);

  server = gethostbyname(targethost);
  if(server == NULL) { return false; }
  memcpy(&addr.sin_addr.s_addr, server->h_addr, (size_t) server->h_length);

  if(connect(ctx->socket, (struct sockaddr *)&addr, sizeof(addr)) != 0)
  {
    return false;
  }

  ctx->fd = fdopen(ctx->socket,"rw");
  if(ctx->fd == NULL) { return false; }

  return true;
}

bool httpc_close_connection(
  httpc_context *ctx
)
{
  if(close(ctx->socket) != 0)
  {
    return false;
  }

  return true;
}

bool httpc_send_request(
  httpc_context *ctx,
  char *request,
  char *response,
  int responsesize
)
{
  int size = strlen(request);
  char lineend[] = " HTTP/1.1\r\n\r\n";

  write(ctx->socket, request, size);
  write(ctx->socket, lineend, sizeof(lineend));

  size = read(ctx->socket, response, responsesize-1);
  response[size] = '\0';

  return true;
}