blob: b01bcb83242f9a85b0992eff74a2ada4f68d14d0 [file] [log] [blame]
brians343bc112013-02-10 01:53:46 +00001#include "aos/common/network/Socket.h"
2
3#include <string.h>
4#include <errno.h>
5
6#include "aos/aos_core.h"
7#include "aos/common/network/SocketLibraries.h"
8
9namespace aos {
10
11int Socket::Connect(NetworkPort port, const char *address, int type) {
12 last_ret_ = 0;
13 if ((socket_ = socket(AF_INET, type, 0)) < 0) {
14 LOG(ERROR, "failed to create socket because of %d: %s\n", errno, strerror(errno));
15 return last_ret_ = 1;
16 }
17
18 memset(&addr_, 0, sizeof(addr_));
19 addr_.in.sin_family = AF_INET;
20 addr_.in.sin_port = htons(static_cast<uint16_t>(port));
21#ifndef __VXWORKS__
22 const int failure_return = 0;
23#else
24 const int failure_return = -1;
25#endif
26 if (inet_aton(lame_unconst(address), &addr_.in.sin_addr) == failure_return) {
27 LOG(ERROR, "Invalid IP address '%s' because of %d: %s\n", address,
28 errno, strerror(errno));
29 return last_ret_ = -1;
30 }
31
32 return last_ret_ = 0;
33}
34Socket::Socket() : socket_(-1), last_ret_(2) {}
35Socket::~Socket() {
36 close(socket_);
37}
38
39void Socket::Reset() {
40 if (socket_ != -1) {
41 close(socket_);
42 socket_ = -1;
43 }
44 last_ret_ = 0;
45}
46
47int Socket::Recv(void *buf, int length) {
48 const int ret = recv(socket_, static_cast<char *>(buf), length, 0);
49 last_ret_ = (ret == -1) ? -1 : 0;
50 return ret;
51}
52int Socket::Recv(void *buf, int length, long usec) {
53 timeval tv;
54 tv.tv_sec = 0;
55 tv.tv_usec = usec;
56 fd_set fds;
57 FD_ZERO(&fds);
58 FD_SET(socket_, &fds);
59 switch (select(FD_SETSIZE, &fds, NULL, NULL, &tv)) {
60 case 1:
61 return Recv(buf, length);
62 case 0:
63 return last_ret_ = 0;
64 default:
65 perror("select on socket to receive from failed");
66 return last_ret_ = -1;
67 }
68}
69int Socket::Send(const void *buf, int length) {
70 const int ret = write(socket_,
71 lame_unconst(static_cast<const char *>(buf)), length);
72 //const int ret = length;
73 last_ret_ = (ret == -1) ? -1 : 0;
74 return ret;
75}
76
77} // namespace aos