source: nanoscale/branches/1.0/clientlib.c @ 4620

Last change on this file since 4620 was 1114, checked in by gah, 13 years ago
File size: 2.1 KB
Line 
1#include <stdio.h>
2#include <unistd.h>
3#include <stdlib.h>
4#include <string.h>
5#include <sys/types.h>
6#include <sys/socket.h>
7#include <sys/time.h>
8#include <netinet/in.h>
9#include <arpa/inet.h>
10#include <netdb.h>
11
12#include "clientlib.h"
13
14int connect_renderer(char *hostname, int connect_port, int memory)
15{
16  int val;
17  int status;
18  struct sockaddr_in connect_addr;
19  int connect_fd = -1;
20
21  struct hostent *hostent = gethostbyname(hostname);
22  if (hostent == NULL) {
23    fprintf(stderr, "Unable to resolve '%s'\n", hostname);
24    return -1;
25  }
26
27  if (hostent->h_addrtype != AF_INET) {
28    fprintf(stderr, "Don't know how to deal with address family for '%s'\n",
29            hostname);
30    return -1;
31  }
32
33  int addr = *(int *) hostent->h_addr_list[0];
34
35 restart:
36
37  // Bind this address to the socket.
38  connect_addr.sin_family = AF_INET;
39  connect_addr.sin_port = htons(connect_port);
40  connect_addr.sin_addr.s_addr = addr; //htonl(inet_network(addr));
41
42  int msg;
43  do {
44    // Create a socket for connecting...
45    connect_fd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
46    if (connect_fd < 0) {
47      perror("socket");
48      return -1;
49    }
50
51    // If program is killed, drop the socket address reservation immediately.
52    val = 1;
53    status = setsockopt(connect_fd, SOL_SOCKET, SO_REUSEADDR, &val, sizeof(val));
54    if (status < 0) {
55      perror("setsockopt");
56      // Not fatal.  Keep on going.
57    }
58
59    // Connect.
60    status = connect(connect_fd, (struct sockaddr *)&connect_addr,
61                     sizeof(connect_addr));
62    if (status < 0) {
63      perror("connect");
64      goto restart;
65    }
66
67    msg = htonl(memory);
68    status = write(connect_fd, &msg, sizeof(msg));
69    if (status <= 0) {
70      perror("write");
71      return -1;
72    }
73
74    status = read(connect_fd, &msg, sizeof(msg));
75    if (status <= 0) {
76      perror("read");
77      return -1;
78    }
79
80    if (msg != 0) {
81      connect_addr.sin_addr.s_addr = msg;
82      fprintf(stderr,"Connection redirected to %s\n",
83              inet_ntoa(connect_addr.sin_addr));
84      status = close(connect_fd);
85      if (status < 0) {
86        perror("shutdown");
87      }
88    }
89  } while(msg != 0);
90
91  return connect_fd;
92}
93
Note: See TracBrowser for help on using the repository browser.