Vowpal Wabbit
network.cc
Go to the documentation of this file.
1 /*
2 Copyright (c) by respective owners including Yahoo!, Microsoft, and
3 individual contributors. All rights reserved. Released under a BSD (revised)
4 license as described in the file LICENSE.
5  */
6 #ifdef _WIN32
7 #define NOMINMAX
8 #include <WinSock2.h>
9 #include <io.h>
10 #else
11 #include <sys/types.h>
12 #include <unistd.h>
13 #include <sys/socket.h>
14 #include <netinet/in.h>
15 #include <netinet/tcp.h>
16 #endif
17 #include <errno.h>
18 #ifndef _WIN32
19 #include <netdb.h>
20 #include <strings.h>
21 #endif
22 #include <string.h>
23 
24 #include <stdlib.h>
25 #include <string>
26 #include <iostream>
27 #include <sstream>
28 #include <stdexcept>
29 #include "vw_exception.h"
30 
31 int open_socket(const char* host)
32 {
33 #ifdef _WIN32
34  const char* colon = strchr(host, ':');
35 #else
36  const char* colon = index(host, ':');
37 #endif
38  short unsigned int port = 26542;
39  hostent* he;
40  if (colon != nullptr)
41  {
42  port = atoi(colon + 1);
43  std::string hostname(host, colon - host);
44  he = gethostbyname(hostname.c_str());
45  }
46  else
47  he = gethostbyname(host);
48 
49  if (he == nullptr)
50  THROWERRNO("gethostbyname(" << host << ")");
51 
52  int sd = (int)socket(PF_INET, SOCK_STREAM, 0);
53  if (sd == -1)
54  THROWERRNO("socket");
55 
56  sockaddr_in far_end;
57  far_end.sin_family = AF_INET;
58  far_end.sin_port = htons(port);
59  far_end.sin_addr = *(in_addr*)(he->h_addr);
60  memset(&far_end.sin_zero, '\0', 8);
61  if (connect(sd, (sockaddr*)&far_end, sizeof(far_end)) == -1)
62  THROWERRNO("connect(" << host << ':' << port << ")");
63 
64  char id = '\0';
65  if (
66 #ifdef _WIN32
67  _write(sd, &id, sizeof(id)) < (int)sizeof(id)
68 #else
69  write(sd, &id, sizeof(id)) < (int)sizeof(id)
70 #endif
71  )
72  std::cerr << "write failed!" << std::endl;
73  return sd;
74 }
#define THROWERRNO(args)
Definition: vw_exception.h:167
int open_socket(const char *host)
Definition: network.cc:31