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
|
/*
Copyright (c) by respective owners including Yahoo!, Microsoft, and
individual contributors. All rights reserved. Released under a BSD (revised)
license as described in the file LICENSE.
*/
#ifdef _WIN32
#include <WinSock2.h>
#include <io.h>
#else
#include <sys/types.h>
#include <unistd.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netinet/tcp.h>
#endif
#include <errno.h>
#ifndef _WIN32
#include <netdb.h>
#include <strings.h>
#endif
#include <stdlib.h>
#include <string.h>
#include <string>
#include <iostream>
using namespace std;
int open_socket(const char* host)
{
#ifdef _WIN32
const char* colon = strchr(host,':');
#else
const char* colon = index(host,':');
#endif
short unsigned int port = 26542;
hostent* he;
if (colon != NULL)
{
port = atoi(colon+1);
string hostname(host,colon-host);
he = gethostbyname(hostname.c_str());
}
else
he = gethostbyname(host);
if (he == NULL)
{
cerr << "can't resolve hostname: " << host << endl;
throw exception();
}
int sd = (int)socket(PF_INET, SOCK_STREAM, 0);
if (sd == -1)
{
cerr << "can't get socket " << endl;
throw exception();
}
sockaddr_in far_end;
far_end.sin_family = AF_INET;
far_end.sin_port = htons(port);
far_end.sin_addr = *(in_addr*)(he->h_addr);
memset(&far_end.sin_zero, '\0',8);
if (connect(sd,(sockaddr*)&far_end, sizeof(far_end)) == -1)
{
#ifdef _WIN32
int err_code = WSAGetLastError();
cerr << "can't connect to: " << host << ":" << port << ". Windows Sockets error code " << err_code << endl;
#else
cerr << "can't connect to: " << host << ':' << port << endl;
#endif
throw exception();
}
char id = '\0';
if (
#ifdef _WIN32
_write(sd, &id, sizeof(id)) < (int)sizeof(id)
#else
write(sd, &id, sizeof(id)) < (int)sizeof(id)
#endif
)
cerr << "write failed!" << endl;
return sd;
}
|