ONPOSIX  2.0
 All Classes Namespaces Files Functions Variables Enumerator Friends Macros Pages
DgramSocketServerDescriptor.cpp
Go to the documentation of this file.
1 /*
2  * DgramSocketServerDescriptor.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>
23 #include "Logger.hpp"
24 
25 
26 namespace onposix {
27 
28 
29 /**
30  * \brief Constructor for local connection-less sockets.
31  *
32  * This constructor creates a connection-less AF_UNIX socket.
33  * It calls socket()+bind().
34  * @param name Name of the local socket on the filesystem
35  * @exception runtime_error in case of error in socket(), bind() or listen()
36  */
38 {
39  // socket()
40  fd_ = socket(AF_UNIX, SOCK_DGRAM, 0);
41  if (fd_ < 0) {
42  ERROR("Socket creation");
43  throw std::runtime_error ("Socket error");
44  }
45 
46  // bind()
47  struct sockaddr_un serv_addr;
48  bzero((char *) &serv_addr, sizeof(serv_addr));
49  serv_addr.sun_family = AF_UNIX;
50  strncpy(serv_addr.sun_path, name.c_str(),
51  sizeof(serv_addr.sun_path) - 1);
52  if (bind(fd_, (struct sockaddr *) &serv_addr, sizeof(serv_addr)) < 0) {
53  ::close(fd_);
54  ERROR("Socket binding");
55  throw std::runtime_error ("Bind error");
56  }
57 }
58 
59 /**
60  * \brief Constructor for UDP sockets.
61  *
62  * This constructor creates a connection-less AF_INET socket.
63  * It calls socket()+bind().
64  * @param port Port of the socket
65  * @exception runtime_error in case of error in socket(), bind() or listen()
66  */
68 {
69  // socket()
70  fd_ = socket(AF_INET, SOCK_DGRAM, 0);
71  if (fd_ < 0) {
72  ERROR("Socket creation");
73  throw std::runtime_error ("Socket error");
74  }
75 
76  // bind()
77  struct sockaddr_in serv_addr;
78  bzero((char *) &serv_addr, sizeof(serv_addr));
79  serv_addr.sin_family = AF_INET;
80  serv_addr.sin_port = htons(port);
81  serv_addr.sin_addr.s_addr = INADDR_ANY;
82  if (bind(fd_, (struct sockaddr *) &serv_addr, sizeof(serv_addr)) < 0) {
83  ::close(fd_);
84  ERROR("Socket binding");
85  throw std::runtime_error ("Bind error");
86  }
87 }
88 
89 } /* onposix */