1 /*
2 * StreamSocketClientDescriptor.cpp
3 *
4 * Copyright (C) 2012 Evidence Srl - www.evidence.eu.com
5 *
6 * This library is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU Library General Public
8 * License as published by the Free Software Foundation; either
9 * version 2 of the License, or (at your option) any later version.
10 *
11 * This library is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 * Library General Public License for more details.
15 *
16 * You should have received a copy of the GNU Library General Public
17 * License along with this library; if not, write to the Free Software
18 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
19 */
20
21 #include <stdexcept>
22 #include <sys/socket.h>
23 #include <netinet/in.h>
24 #include <arpa/inet.h>
25
28
29 namespace onposix {
30
31 /**
32 * \brief Constructor for local (i.e., AF_UNIX) sockets.
33 *
34 * It calls socket()+connect().
35 * @param name Name of the local socket on the filesystem
36 * @exception runtime_error in case of error in socket() or connect()
37 */
39 {
40 // socket()
41 fd_ = socket(AF_UNIX, SOCK_STREAM, 0);
43 ERROR(
"Creating client socket");
44 throw std::runtime_error ("Client socket error");
45 }
46
47 // connect()
48 struct sockaddr_un serv_addr;
49 bzero((char *) &serv_addr, sizeof(serv_addr));
50 serv_addr.sun_family = AF_UNIX;
51 strncpy(serv_addr.sun_path, name.c_str(), sizeof(serv_addr.sun_path) - 1);
52 if (connect(
fd_, (
struct sockaddr *) &serv_addr,
53 sizeof(serv_addr)) < 0) {
56 throw std::runtime_error ("Client socket error");
57 }
58 }
59
60
61 /**
62 * \brief Constructor for TCP (i.e., AF_INET) sockets.
63 *
64 * It calls socket()+connect().
65 * @param port Port of the socket
66 * @exception runtime_error in case of error in socket() or connect()
67 */
69 const uint16_t port)
70 {
71 // socket()
72 fd_ = socket(AF_INET, SOCK_STREAM, 0);
74 ERROR(
"Creating client socket");
75 throw std::runtime_error ("Client socket error");
76 }
77
78 // connect()
79 struct sockaddr_in serv_addr;
80 bzero((char *) &serv_addr, sizeof(serv_addr));
81 serv_addr.sin_family = AF_INET;
82 serv_addr.sin_port = htons(port);
83
84 struct in_addr addr;
85 inet_aton(address.c_str(), &addr);
86 bcopy(&addr, &serv_addr.sin_addr.s_addr, sizeof(addr));
87
88 if (connect(
fd_, (
struct sockaddr *) &serv_addr,
89 sizeof(serv_addr)) < 0) {
92 throw std::runtime_error ("Client socket error");
93 }
94
95 }
96
97 } /* onposix */