int BSocket::getFd(){
return osocket;
}
BError BSocket::bind(const BSocketAddress& address){
BError err;
if(::bind(osocket, address, address.len()) < 0)
err.set(-errno, strerror(errno));
return err;
}
BError BSocket::connect(const BSocketAddress& address){
BError err;
if(::connect(osocket, address, address.len()) < 0)
err.set(-errno, strerror(errno));
return err;
}
BError BSocket::shutdown(int how){
BError err;
if(::shutdown(osocket, how) < 0)
err.set(-errno, strerror(errno));
return err;
}
BError BSocket::close(){
BError err;
if(osocket >= 0)
::close(osocket);
osocket = -1;
return err;
}
BError BSocket::listen(int backlog){
BError err;
if(::listen(osocket, 5) < 0)
err.set(-errno, strerror(errno));
return err;
}
BError BSocket::accept(int& fd){
BError err;
int f;
if((f = ::accept(osocket, 0, 0)) < 0){
err.set(-errno, strerror(errno));
}
else {
fd = f;
}
return err;
}
BError BSocket::accept(int& fd, BSocketAddress& address){
BError err;
BSocketAddress::SockAddr add;
socklen_t len = sizeof(add);
int f;
if((f = ::accept(osocket, &add, &len)) < 0){
err.set(-errno, strerror(errno));
}
else {
fd = f;
address.set(&add, len);
}
return err;
}
BError BSocket::send(const void* buf, BSize nbytes, BSize& nbytesSent, int flags){
BError err;
int r;
if((r = ::send(osocket, buf, nbytes, flags)) < 0){
err.set(-errno, strerror(errno));
}
else {
nbytesSent = r;
}
return err;
}
BError BSocket::sendTo(const BSocketAddress& address, const void* buf, BSize nbytes, BSize& nbytesSent, int flags){
BError err;
int r;
if((r = ::sendto(osocket, buf, nbytes, flags, address, address.len())) < 0){
err.set(-errno, strerror(errno));
}
else {
nbytesSent = r;
}
return err;
}
BError BSocket::recv(void* buf, BSize maxbytes, BSize& nbytesRecv, int flags){
BError err;
int r;
if((r = ::recv(osocket, buf, maxbytes, flags)) < 0){
err.set(-errno, strerror(errno));
}
else {
if(r == 0)
err.set(-EPIPE, "Connection Closed by Peer");
nbytesRecv = r;
}
return err;
}
BError BSocket::recvWithTimeout(void* buf, BSize maxbytes, BSize& nbytesRecv, int timeout, int flags){
BError err;
int r;
fd_set set;
struct timeval t;
if(timeout >= 0){
t.tv_sec = 0;
t.tv_usec = timeout;
FD_ZERO(&set);
FD_SET(osocket, &set);
r = select(osocket + 1, &set, 0, 0, &t);
if(r == 0)
return err.set(-ETIMEDOUT, "Connection timed out");
}
return recv(buf, maxbytes, nbytesRecv, flags);
}
BError BSocket::recvFrom(BSocketAddress& address, void* buf, BSize maxbytes, BSize& nbytesRecv, int flags){
BError err;
int r;
BSocketAddress::SockAddr add;
socklen_t len = sizeof(add);
if((r = ::recvfrom(osocket, buf, maxbytes, flags, &add, &len)) < 0){
err.set(-errno, strerror(errno));
}
else {
address.set(&add, len);