1 #ifndef MPQC_ARRAY_SOCKET_HPP
2 #define MPQC_ARRAY_SOCKET_HPP
5 #include <sys/socket.h>
6 #include <netinet/in.h>
18 typedef sockaddr Address;
20 static void assert_(
bool cond,
const std::string &msg) {
23 throw std::runtime_error(msg +
" failed");
58 assert_(::gethostname(hostname,
sizeof(hostname)) > -1,
"gethostname");
59 assert_((h = ::gethostbyname(hostname)),
"gethostbyname");
60 if (h->h_addrtype == AF_INET) {
61 in = *(in_addr*)h->h_addr;
68 struct sockaddr_in sin;
69 sin.sin_family = AF_INET;
71 sin.sin_addr.s_addr =
in.s_addr;
72 memset(sin.sin_zero,
'\0',
sizeof(sin.sin_zero));
75 assert_((sock = ::socket(PF_INET, SOCK_STREAM, 0)) > -1,
"socket");
76 assert_(::bind(sock, (
struct sockaddr*)&sin,
sizeof(sin)) > -1,
"bind");
77 assert_(::listen(sock, 10) > -1,
"listen");
82 Address addr = this->address();
83 printf(
"ArrayServer running on %s:%i\n",
84 inet_ntoa(((sockaddr_in*)&addr)->sin_addr),
85 ((sockaddr_in*)&addr)->sin_port);
90 Address address()
const {
92 socklen_t len =
sizeof(addr);
93 assert_(getsockname(this->fd_, &addr, &len) > -1,
"getsockname");
98 void wait(T *data)
const {
99 struct sockaddr_storage addr;
100 socklen_t addrlen =
sizeof(addr);
102 assert_((fd = ::accept(this->fd_, (sockaddr*)&addr, &addrlen)) > -1,
104 assert_((bytes = ::recv(fd, data,
sizeof(T), 0)) > -1,
"recv");
105 assert_(::close(fd) > -1,
"close");
106 if (bytes !=
sizeof(T)) {
107 throw std::runtime_error(
"wrong number of bytes received");
112 static void send(
const T *data,
struct sockaddr addr) {
114 assert_((fd = ::socket(AF_INET, SOCK_STREAM, 0)) > -1,
"socket");
115 assert_(::connect(fd, &addr,
sizeof(addr)) > -1,
"connect");
116 assert_(::send(fd, data,
sizeof(T), 0) > -1,
"send");
117 assert_(::close(fd) > -1,
"close");
128 #endif // MPQC_ARRAY_SOCKET_HPP