Reformat source
This commit is contained in:
parent
15fe1a928a
commit
5df7c881b9
552
Socket.cpp
552
Socket.cpp
@ -2,15 +2,15 @@
|
||||
#include "Socket.h"
|
||||
|
||||
|
||||
#include <sys/types.h> // For data types
|
||||
#include <sys/socket.h> // For socket(), connect(), send(), and recv()
|
||||
#include <netdb.h> // For gethostbyname()
|
||||
#include <arpa/inet.h> // For inet_addr()
|
||||
#include <unistd.h> // For close()
|
||||
#include <netinet/in.h> // For sockaddr_in
|
||||
#include <netinet/tcp.h> // TCP_KEEPCNT
|
||||
#include <fcntl.h>
|
||||
typedef void raw_type; // Type used for raw data on this platform
|
||||
#include <sys/types.h> // For data types
|
||||
#include <sys/socket.h> // For socket(), connect(), send(), and recv()
|
||||
#include <netdb.h> // For gethostbyname()
|
||||
#include <arpa/inet.h> // For inet_addr()
|
||||
#include <unistd.h> // For close()
|
||||
#include <netinet/in.h> // For sockaddr_in
|
||||
#include <netinet/tcp.h> // TCP_KEEPCNT
|
||||
#include <fcntl.h>
|
||||
typedef void raw_type; // Type used for raw data on this platform
|
||||
|
||||
#include <errno.h> // For errno
|
||||
|
||||
@ -19,126 +19,146 @@ using namespace std;
|
||||
// SocketException Code
|
||||
|
||||
SocketException::SocketException(const string &message, bool inclSysMsg)
|
||||
: userMessage(message) {
|
||||
if (inclSysMsg) {
|
||||
userMessage.append(": ");
|
||||
userMessage.append(strerror(errno));
|
||||
}
|
||||
: userMessage(message)
|
||||
{
|
||||
if (inclSysMsg)
|
||||
{
|
||||
userMessage.append(": ");
|
||||
userMessage.append(strerror(errno));
|
||||
}
|
||||
}
|
||||
|
||||
SocketException::~SocketException() noexcept (true) {
|
||||
SocketException::~SocketException() noexcept (true)
|
||||
{
|
||||
}
|
||||
|
||||
const char *SocketException::what(){
|
||||
return userMessage.c_str();
|
||||
const char *SocketException::what()
|
||||
{
|
||||
return userMessage.c_str();
|
||||
}
|
||||
|
||||
// Function to fill in address structure given an address and port
|
||||
static void fillAddr(const string &address, unsigned short port,
|
||||
sockaddr_in &addr) {
|
||||
memset(&addr, 0, sizeof(addr)); // Zero out address structure
|
||||
addr.sin_family = AF_INET; // Internet address
|
||||
static void fillAddr(const string &address, unsigned short port,
|
||||
sockaddr_in &addr)
|
||||
{
|
||||
memset(&addr, 0, sizeof(addr)); // Zero out address structure
|
||||
addr.sin_family = AF_INET; // Internet address
|
||||
|
||||
hostent *host; // Resolve name
|
||||
if ((host = gethostbyname(address.c_str())) == NULL) {
|
||||
// strerror() will not work for gethostbyname() and hstrerror()
|
||||
// is supposedly obsolete
|
||||
throw SocketException("Failed to resolve name (gethostbyname())");
|
||||
}
|
||||
addr.sin_addr.s_addr = *((unsigned long *) host->h_addr_list[0]);
|
||||
hostent *host; // Resolve name
|
||||
if ((host = gethostbyname(address.c_str())) == NULL)
|
||||
{
|
||||
// strerror() will not work for gethostbyname() and hstrerror()
|
||||
// is supposedly obsolete
|
||||
throw SocketException("Failed to resolve name (gethostbyname())");
|
||||
}
|
||||
addr.sin_addr.s_addr = *((unsigned long *) host->h_addr_list[0]);
|
||||
|
||||
addr.sin_port = htons(port); // Assign port in network byte order
|
||||
addr.sin_port = htons(port); // Assign port in network byte order
|
||||
}
|
||||
|
||||
// Socket Code
|
||||
|
||||
Socket::Socket(int type, int protocol) {
|
||||
|
||||
// Make a new socket
|
||||
if ((sockDesc = socket(PF_INET, type, protocol)) < 0) {
|
||||
throw SocketException("Socket creation failed (socket())", true);
|
||||
}
|
||||
}
|
||||
|
||||
Socket::Socket(int sockDesc) {
|
||||
this->sockDesc = sockDesc;
|
||||
}
|
||||
|
||||
Socket::~Socket()
|
||||
Socket::Socket(int type, int protocol)
|
||||
{
|
||||
close(sockDesc);
|
||||
sockDesc = -1;
|
||||
|
||||
// Make a new socket
|
||||
if ((sockDesc = socket(PF_INET, type, protocol)) < 0)
|
||||
{
|
||||
throw SocketException("Socket creation failed (socket())", true);
|
||||
}
|
||||
}
|
||||
|
||||
string Socket::getLocalAddress() {
|
||||
sockaddr_in addr;
|
||||
unsigned int addr_len = sizeof(addr);
|
||||
|
||||
if (getsockname(sockDesc, (sockaddr *) &addr, (socklen_t *) &addr_len) < 0) {
|
||||
throw SocketException("Fetch of local address failed (getsockname())", true);
|
||||
}
|
||||
return inet_ntoa(addr.sin_addr);
|
||||
Socket::Socket(int sockDesc)
|
||||
{
|
||||
this->sockDesc = sockDesc;
|
||||
}
|
||||
|
||||
unsigned short Socket::getLocalPort() {
|
||||
sockaddr_in addr;
|
||||
unsigned int addr_len = sizeof(addr);
|
||||
|
||||
if (getsockname(sockDesc, (sockaddr *) &addr, (socklen_t *) &addr_len) < 0) {
|
||||
throw SocketException("Fetch of local port failed (getsockname())", true);
|
||||
}
|
||||
return ntohs(addr.sin_port);
|
||||
Socket::~Socket()
|
||||
{
|
||||
close(sockDesc);
|
||||
sockDesc = -1;
|
||||
}
|
||||
|
||||
void Socket::setLocalPort(unsigned short localPort) {
|
||||
// Bind the socket to its port
|
||||
sockaddr_in localAddr;
|
||||
memset(&localAddr, 0, sizeof(localAddr));
|
||||
localAddr.sin_family = AF_INET;
|
||||
localAddr.sin_addr.s_addr = htonl(INADDR_ANY);
|
||||
localAddr.sin_port = htons(localPort);
|
||||
string Socket::getLocalAddress()
|
||||
{
|
||||
sockaddr_in addr;
|
||||
unsigned int addr_len = sizeof(addr);
|
||||
|
||||
if (bind(sockDesc, (sockaddr *) &localAddr, sizeof(sockaddr_in)) < 0) {
|
||||
throw SocketException("Set of local port failed (bind())", true);
|
||||
}
|
||||
if (getsockname(sockDesc, (sockaddr *) &addr, (socklen_t *) &addr_len) < 0)
|
||||
{
|
||||
throw SocketException("Fetch of local address failed (getsockname())", true);
|
||||
}
|
||||
return inet_ntoa(addr.sin_addr);
|
||||
}
|
||||
|
||||
unsigned short Socket::getLocalPort()
|
||||
{
|
||||
sockaddr_in addr;
|
||||
unsigned int addr_len = sizeof(addr);
|
||||
|
||||
if (getsockname(sockDesc, (sockaddr *) &addr, (socklen_t *) &addr_len) < 0)
|
||||
{
|
||||
throw SocketException("Fetch of local port failed (getsockname())", true);
|
||||
}
|
||||
return ntohs(addr.sin_port);
|
||||
}
|
||||
|
||||
void Socket::setLocalPort(unsigned short localPort)
|
||||
{
|
||||
// Bind the socket to its port
|
||||
sockaddr_in localAddr;
|
||||
memset(&localAddr, 0, sizeof(localAddr));
|
||||
localAddr.sin_family = AF_INET;
|
||||
localAddr.sin_addr.s_addr = htonl(INADDR_ANY);
|
||||
localAddr.sin_port = htons(localPort);
|
||||
|
||||
if (bind(sockDesc, (sockaddr *) &localAddr, sizeof(sockaddr_in)) < 0)
|
||||
{
|
||||
throw SocketException("Set of local port failed (bind())", true);
|
||||
}
|
||||
}
|
||||
|
||||
void Socket::setLocalAddressAndPort(const string &localAddress,
|
||||
unsigned short localPort) {
|
||||
// Get the address of the requested host
|
||||
sockaddr_in localAddr;
|
||||
fillAddr(localAddress, localPort, localAddr);
|
||||
unsigned short localPort)
|
||||
{
|
||||
// Get the address of the requested host
|
||||
sockaddr_in localAddr;
|
||||
fillAddr(localAddress, localPort, localAddr);
|
||||
|
||||
if (bind(sockDesc, (sockaddr *) &localAddr, sizeof(sockaddr_in)) < 0) {
|
||||
throw SocketException("Set of local address and port failed (bind())", true);
|
||||
}
|
||||
if (bind(sockDesc, (sockaddr *) &localAddr, sizeof(sockaddr_in)) < 0)
|
||||
{
|
||||
throw SocketException("Set of local address and port failed (bind())", true);
|
||||
}
|
||||
}
|
||||
|
||||
void Socket::setKeepalive()
|
||||
{
|
||||
int optval = 1;
|
||||
setsockopt(sockDesc, SOL_SOCKET, SO_KEEPALIVE,&optval, sizeof(optval));
|
||||
|
||||
optval = 2;
|
||||
setsockopt(sockDesc, SOL_SOCKET, TCP_KEEPCNT, &optval, sizeof(optval));
|
||||
|
||||
optval = 10;
|
||||
setsockopt(sockDesc, SOL_SOCKET, TCP_KEEPIDLE, &optval, sizeof(optval));
|
||||
|
||||
optval = 5;
|
||||
setsockopt(sockDesc, SOL_SOCKET, TCP_KEEPINTVL, &optval, sizeof(optval));
|
||||
int optval = 1;
|
||||
setsockopt(sockDesc, SOL_SOCKET, SO_KEEPALIVE,&optval, sizeof(optval));
|
||||
|
||||
optval = 2;
|
||||
setsockopt(sockDesc, SOL_SOCKET, TCP_KEEPCNT, &optval, sizeof(optval));
|
||||
|
||||
optval = 10;
|
||||
setsockopt(sockDesc, SOL_SOCKET, TCP_KEEPIDLE, &optval, sizeof(optval));
|
||||
|
||||
optval = 5;
|
||||
setsockopt(sockDesc, SOL_SOCKET, TCP_KEEPINTVL, &optval, sizeof(optval));
|
||||
}
|
||||
|
||||
void Socket::setBlocking(bool flag)
|
||||
{
|
||||
int flags = fcntl(sockDesc, F_GETFL, 0);
|
||||
if( !flag ) flags = flags | O_NONBLOCK;
|
||||
else flags = flags & ~O_NONBLOCK;
|
||||
fcntl(sockDesc, F_SETFL, flags);
|
||||
int flags = fcntl(sockDesc, F_GETFL, 0);
|
||||
if( !flag )
|
||||
flags = flags | O_NONBLOCK;
|
||||
else
|
||||
flags = flags & ~O_NONBLOCK;
|
||||
fcntl(sockDesc, F_SETFL, flags);
|
||||
}
|
||||
|
||||
void Socket::cleanUp() {
|
||||
|
||||
void Socket::cleanUp()
|
||||
{
|
||||
|
||||
}
|
||||
|
||||
int Socket::getFD()
|
||||
@ -147,229 +167,263 @@ int Socket::getFD()
|
||||
}
|
||||
|
||||
unsigned short Socket::resolveService(const string &service,
|
||||
const string &protocol) {
|
||||
struct servent *serv; /* Structure containing service information */
|
||||
const string &protocol)
|
||||
{
|
||||
struct servent *serv; /* Structure containing service information */
|
||||
|
||||
if ((serv = getservbyname(service.c_str(), protocol.c_str())) == NULL)
|
||||
return atoi(service.c_str()); /* Service is port number */
|
||||
else
|
||||
return ntohs(serv->s_port); /* Found port (network byte order) by name */
|
||||
if ((serv = getservbyname(service.c_str(), protocol.c_str())) == NULL)
|
||||
return atoi(service.c_str()); /* Service is port number */
|
||||
else
|
||||
return ntohs(serv->s_port); /* Found port (network byte order) by name */
|
||||
}
|
||||
|
||||
// CommunicatingSocket Code
|
||||
|
||||
CommunicatingSocket::CommunicatingSocket(int type, int protocol)
|
||||
: Socket(type, protocol) {
|
||||
CommunicatingSocket::CommunicatingSocket(int type, int protocol)
|
||||
: Socket(type, protocol)
|
||||
{
|
||||
}
|
||||
|
||||
CommunicatingSocket::CommunicatingSocket(int newConnSD) : Socket(newConnSD) {
|
||||
CommunicatingSocket::CommunicatingSocket(int newConnSD) : Socket(newConnSD)
|
||||
{
|
||||
}
|
||||
|
||||
void CommunicatingSocket::connect(const string &foreignAddress,
|
||||
unsigned short foreignPort) {
|
||||
// Get the address of the requested host
|
||||
sockaddr_in destAddr;
|
||||
fillAddr(foreignAddress, foreignPort, destAddr);
|
||||
|
||||
// Try to connect to the given port
|
||||
if (::connect(sockDesc, (sockaddr *) &destAddr, sizeof(destAddr)) < 0) {
|
||||
throw SocketException("Connect failed (connect())", true);
|
||||
}
|
||||
}
|
||||
|
||||
void CommunicatingSocket::send(const void *buffer, int bufferLen)
|
||||
{
|
||||
if (::send(sockDesc, (raw_type *) buffer, bufferLen, 0) < 0) {
|
||||
throw SocketException("Send failed (send())", true);
|
||||
}
|
||||
}
|
||||
|
||||
int CommunicatingSocket::recv(void *buffer, int bufferLen)
|
||||
unsigned short foreignPort)
|
||||
{
|
||||
int rtn;
|
||||
if ((rtn = ::recv(sockDesc, (raw_type *) buffer, bufferLen, MSG_DONTWAIT)) < 0 )
|
||||
{
|
||||
if(errno == EWOULDBLOCK || errno == EAGAIN) return -1;
|
||||
else throw SocketException("Received failed (recv())", true);
|
||||
}
|
||||
// Get the address of the requested host
|
||||
sockaddr_in destAddr;
|
||||
fillAddr(foreignAddress, foreignPort, destAddr);
|
||||
|
||||
return rtn;
|
||||
// Try to connect to the given port
|
||||
if (::connect(sockDesc, (sockaddr *) &destAddr, sizeof(destAddr)) < 0)
|
||||
{
|
||||
throw SocketException("Connect failed (connect())", true);
|
||||
}
|
||||
}
|
||||
|
||||
string CommunicatingSocket::getForeignAddress()
|
||||
{
|
||||
sockaddr_in addr;
|
||||
unsigned int addr_len = sizeof(addr);
|
||||
|
||||
if (getpeername(sockDesc, (sockaddr *) &addr,(socklen_t *) &addr_len) < 0) {
|
||||
throw SocketException("Fetch of foreign address failed (getpeername())", true);
|
||||
}
|
||||
return inet_ntoa(addr.sin_addr);
|
||||
void CommunicatingSocket::send(const void *buffer, int bufferLen)
|
||||
{
|
||||
if (::send(sockDesc, (raw_type *) buffer, bufferLen, 0) < 0)
|
||||
{
|
||||
throw SocketException("Send failed (send())", true);
|
||||
}
|
||||
}
|
||||
|
||||
unsigned short CommunicatingSocket::getForeignPort() {
|
||||
sockaddr_in addr;
|
||||
unsigned int addr_len = sizeof(addr);
|
||||
int CommunicatingSocket::recv(void *buffer, int bufferLen)
|
||||
{
|
||||
int rtn;
|
||||
if ((rtn = ::recv(sockDesc, (raw_type *) buffer, bufferLen, MSG_DONTWAIT)) < 0 )
|
||||
{
|
||||
if(errno == EWOULDBLOCK || errno == EAGAIN)
|
||||
return -1;
|
||||
else
|
||||
throw SocketException("Received failed (recv())", true);
|
||||
}
|
||||
|
||||
if (getpeername(sockDesc, (sockaddr *) &addr, (socklen_t *) &addr_len) < 0) {
|
||||
throw SocketException("Fetch of foreign port failed (getpeername())", true);
|
||||
}
|
||||
return ntohs(addr.sin_port);
|
||||
return rtn;
|
||||
}
|
||||
|
||||
string CommunicatingSocket::getForeignAddress()
|
||||
{
|
||||
sockaddr_in addr;
|
||||
unsigned int addr_len = sizeof(addr);
|
||||
|
||||
if (getpeername(sockDesc, (sockaddr *) &addr,(socklen_t *) &addr_len) < 0)
|
||||
{
|
||||
throw SocketException("Fetch of foreign address failed (getpeername())", true);
|
||||
}
|
||||
return inet_ntoa(addr.sin_addr);
|
||||
}
|
||||
|
||||
unsigned short CommunicatingSocket::getForeignPort()
|
||||
{
|
||||
sockaddr_in addr;
|
||||
unsigned int addr_len = sizeof(addr);
|
||||
|
||||
if (getpeername(sockDesc, (sockaddr *) &addr, (socklen_t *) &addr_len) < 0)
|
||||
{
|
||||
throw SocketException("Fetch of foreign port failed (getpeername())", true);
|
||||
}
|
||||
return ntohs(addr.sin_port);
|
||||
}
|
||||
|
||||
// TCPSocket Code
|
||||
|
||||
TCPSocket::TCPSocket()
|
||||
: CommunicatingSocket(SOCK_STREAM,
|
||||
IPPROTO_TCP) {
|
||||
TCPSocket::TCPSocket()
|
||||
: CommunicatingSocket(SOCK_STREAM,
|
||||
IPPROTO_TCP)
|
||||
{
|
||||
}
|
||||
|
||||
TCPSocket::TCPSocket(const string &foreignAddress, unsigned short foreignPort, bool keepalive)
|
||||
: CommunicatingSocket(SOCK_STREAM, IPPROTO_TCP) {
|
||||
connect(foreignAddress, foreignPort);
|
||||
if(keepalive) setKeepalive();
|
||||
: CommunicatingSocket(SOCK_STREAM, IPPROTO_TCP)
|
||||
{
|
||||
connect(foreignAddress, foreignPort);
|
||||
if(keepalive)
|
||||
setKeepalive();
|
||||
}
|
||||
|
||||
TCPSocket::TCPSocket(int newConnSD) : CommunicatingSocket(newConnSD) {
|
||||
TCPSocket::TCPSocket(int newConnSD) : CommunicatingSocket(newConnSD)
|
||||
{
|
||||
}
|
||||
|
||||
// TCPServerSocket Code
|
||||
|
||||
TCPServerSocket::TCPServerSocket(unsigned short localPort, int queueLen, bool keepaliveIN)
|
||||
: Socket(SOCK_STREAM, IPPROTO_TCP)
|
||||
TCPServerSocket::TCPServerSocket(unsigned short localPort, int queueLen, bool keepaliveIN)
|
||||
: Socket(SOCK_STREAM, IPPROTO_TCP)
|
||||
{
|
||||
keepalive = keepaliveIN;
|
||||
setLocalPort(localPort);
|
||||
setListen(queueLen);
|
||||
keepalive = keepaliveIN;
|
||||
setLocalPort(localPort);
|
||||
setListen(queueLen);
|
||||
}
|
||||
|
||||
TCPServerSocket::TCPServerSocket(const string &localAddress, unsigned short localPort, int queueLen, bool keepaliveIN)
|
||||
: Socket(SOCK_STREAM, IPPROTO_TCP)
|
||||
TCPServerSocket::TCPServerSocket(const string &localAddress, unsigned short localPort, int queueLen, bool keepaliveIN)
|
||||
: Socket(SOCK_STREAM, IPPROTO_TCP)
|
||||
{
|
||||
keepalive = keepaliveIN;
|
||||
setLocalAddressAndPort(localAddress, localPort);
|
||||
setListen(queueLen);
|
||||
keepalive = keepaliveIN;
|
||||
setLocalAddressAndPort(localAddress, localPort);
|
||||
setListen(queueLen);
|
||||
}
|
||||
|
||||
TCPSocket* TCPServerSocket::accept()
|
||||
TCPSocket* TCPServerSocket::accept()
|
||||
{
|
||||
int newConnSD = -1;
|
||||
if ((newConnSD = ::accept(sockDesc, NULL, 0)) < 0 && errno != EAGAIN && errno != EWOULDBLOCK )
|
||||
{
|
||||
throw SocketException("Accept failed (accept())", true);
|
||||
}
|
||||
TCPSocket* newSocket = nullptr;
|
||||
if(newConnSD > 0)
|
||||
{
|
||||
newSocket = new TCPSocket(newConnSD);
|
||||
if(keepalive) newSocket->setKeepalive();
|
||||
}
|
||||
return newSocket;
|
||||
int newConnSD = -1;
|
||||
if ((newConnSD = ::accept(sockDesc, NULL, 0)) < 0 && errno != EAGAIN && errno != EWOULDBLOCK )
|
||||
{
|
||||
throw SocketException("Accept failed (accept())", true);
|
||||
}
|
||||
TCPSocket* newSocket = nullptr;
|
||||
if(newConnSD > 0)
|
||||
{
|
||||
newSocket = new TCPSocket(newConnSD);
|
||||
if(keepalive)
|
||||
newSocket->setKeepalive();
|
||||
}
|
||||
return newSocket;
|
||||
}
|
||||
|
||||
|
||||
|
||||
void TCPServerSocket::setListen(int queueLen) {
|
||||
if (listen(sockDesc, queueLen) < 0) {
|
||||
throw SocketException("Set listening socket failed (listen())", true);
|
||||
}
|
||||
void TCPServerSocket::setListen(int queueLen)
|
||||
{
|
||||
if (listen(sockDesc, queueLen) < 0)
|
||||
{
|
||||
throw SocketException("Set listening socket failed (listen())", true);
|
||||
}
|
||||
}
|
||||
|
||||
// UDPSocket Code
|
||||
|
||||
UDPSocket::UDPSocket() : CommunicatingSocket(SOCK_DGRAM,
|
||||
IPPROTO_UDP) {
|
||||
setBroadcast();
|
||||
IPPROTO_UDP)
|
||||
{
|
||||
setBroadcast();
|
||||
}
|
||||
|
||||
UDPSocket::UDPSocket(unsigned short localPort) :
|
||||
CommunicatingSocket(SOCK_DGRAM, IPPROTO_UDP) {
|
||||
setLocalPort(localPort);
|
||||
setBroadcast();
|
||||
UDPSocket::UDPSocket(unsigned short localPort) :
|
||||
CommunicatingSocket(SOCK_DGRAM, IPPROTO_UDP)
|
||||
{
|
||||
setLocalPort(localPort);
|
||||
setBroadcast();
|
||||
}
|
||||
|
||||
UDPSocket::UDPSocket(const string &localAddress, unsigned short localPort)
|
||||
: CommunicatingSocket(SOCK_DGRAM, IPPROTO_UDP) {
|
||||
setLocalAddressAndPort(localAddress, localPort);
|
||||
setBroadcast();
|
||||
UDPSocket::UDPSocket(const string &localAddress, unsigned short localPort)
|
||||
: CommunicatingSocket(SOCK_DGRAM, IPPROTO_UDP)
|
||||
{
|
||||
setLocalAddressAndPort(localAddress, localPort);
|
||||
setBroadcast();
|
||||
}
|
||||
|
||||
void UDPSocket::setBroadcast() {
|
||||
// If this fails, we'll hear about it when we try to send. This will allow
|
||||
// system that cannot broadcast to continue if they don't plan to broadcast
|
||||
int broadcastPermission = 1;
|
||||
setsockopt(sockDesc, SOL_SOCKET, SO_BROADCAST,
|
||||
(raw_type *) &broadcastPermission, sizeof(broadcastPermission));
|
||||
void UDPSocket::setBroadcast()
|
||||
{
|
||||
// If this fails, we'll hear about it when we try to send. This will allow
|
||||
// system that cannot broadcast to continue if they don't plan to broadcast
|
||||
int broadcastPermission = 1;
|
||||
setsockopt(sockDesc, SOL_SOCKET, SO_BROADCAST,
|
||||
(raw_type *) &broadcastPermission, sizeof(broadcastPermission));
|
||||
}
|
||||
|
||||
void UDPSocket::disconnect() {
|
||||
sockaddr_in nullAddr;
|
||||
memset(&nullAddr, 0, sizeof(nullAddr));
|
||||
nullAddr.sin_family = AF_UNSPEC;
|
||||
void UDPSocket::disconnect()
|
||||
{
|
||||
sockaddr_in nullAddr;
|
||||
memset(&nullAddr, 0, sizeof(nullAddr));
|
||||
nullAddr.sin_family = AF_UNSPEC;
|
||||
|
||||
// Try to disconnect
|
||||
if (::connect(sockDesc, (sockaddr *) &nullAddr, sizeof(nullAddr)) < 0) {
|
||||
if (errno != EAFNOSUPPORT) {
|
||||
throw SocketException("Disconnect failed (connect())", true);
|
||||
}
|
||||
}
|
||||
// Try to disconnect
|
||||
if (::connect(sockDesc, (sockaddr *) &nullAddr, sizeof(nullAddr)) < 0)
|
||||
{
|
||||
if (errno != EAFNOSUPPORT)
|
||||
{
|
||||
throw SocketException("Disconnect failed (connect())", true);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void UDPSocket::sendTo(const void *buffer, int bufferLen,
|
||||
const string &foreignAddress, unsigned short foreignPort)
|
||||
{
|
||||
sockaddr_in destAddr;
|
||||
fillAddr(foreignAddress, foreignPort, destAddr);
|
||||
void UDPSocket::sendTo(const void *buffer, int bufferLen,
|
||||
const string &foreignAddress, unsigned short foreignPort)
|
||||
{
|
||||
sockaddr_in destAddr;
|
||||
fillAddr(foreignAddress, foreignPort, destAddr);
|
||||
|
||||
// Write out the whole buffer as a single message.
|
||||
if (sendto(sockDesc, (raw_type *) buffer, bufferLen, 0,
|
||||
(sockaddr *) &destAddr, sizeof(destAddr)) != bufferLen) {
|
||||
throw SocketException("Send failed (sendto())", true);
|
||||
}
|
||||
// Write out the whole buffer as a single message.
|
||||
if (sendto(sockDesc, (raw_type *) buffer, bufferLen, 0,
|
||||
(sockaddr *) &destAddr, sizeof(destAddr)) != bufferLen)
|
||||
{
|
||||
throw SocketException("Send failed (sendto())", true);
|
||||
}
|
||||
}
|
||||
|
||||
int UDPSocket::recvFrom(void *buffer, int bufferLen, string &sourceAddress,
|
||||
unsigned short &sourcePort) {
|
||||
sockaddr_in clntAddr;
|
||||
socklen_t addrLen = sizeof(clntAddr);
|
||||
int rtn;
|
||||
if ((rtn = recvfrom(sockDesc, (raw_type *) buffer, bufferLen, MSG_DONTWAIT, (sockaddr *) &clntAddr, (socklen_t *) &addrLen)) < 0)
|
||||
{
|
||||
throw SocketException("Receive failed (recvfrom())", true);
|
||||
}
|
||||
sourceAddress = inet_ntoa(clntAddr.sin_addr);
|
||||
sourcePort = ntohs(clntAddr.sin_port);
|
||||
unsigned short &sourcePort)
|
||||
{
|
||||
sockaddr_in clntAddr;
|
||||
socklen_t addrLen = sizeof(clntAddr);
|
||||
int rtn;
|
||||
if ((rtn = recvfrom(sockDesc, (raw_type *) buffer, bufferLen, MSG_DONTWAIT, (sockaddr *) &clntAddr,
|
||||
(socklen_t *) &addrLen)) < 0)
|
||||
{
|
||||
throw SocketException("Receive failed (recvfrom())", true);
|
||||
}
|
||||
sourceAddress = inet_ntoa(clntAddr.sin_addr);
|
||||
sourcePort = ntohs(clntAddr.sin_port);
|
||||
|
||||
return rtn;
|
||||
return rtn;
|
||||
}
|
||||
|
||||
void UDPSocket::setMulticastTTL(unsigned char multicastTTL) {
|
||||
if (setsockopt(sockDesc, IPPROTO_IP, IP_MULTICAST_TTL,
|
||||
(raw_type *) &multicastTTL, sizeof(multicastTTL)) < 0) {
|
||||
throw SocketException("Multicast TTL set failed (setsockopt())", true);
|
||||
}
|
||||
void UDPSocket::setMulticastTTL(unsigned char multicastTTL)
|
||||
{
|
||||
if (setsockopt(sockDesc, IPPROTO_IP, IP_MULTICAST_TTL,
|
||||
(raw_type *) &multicastTTL, sizeof(multicastTTL)) < 0)
|
||||
{
|
||||
throw SocketException("Multicast TTL set failed (setsockopt())", true);
|
||||
}
|
||||
}
|
||||
|
||||
void UDPSocket::joinGroup(const string &multicastGroup) {
|
||||
struct ip_mreq multicastRequest;
|
||||
void UDPSocket::joinGroup(const string &multicastGroup)
|
||||
{
|
||||
struct ip_mreq multicastRequest;
|
||||
|
||||
multicastRequest.imr_multiaddr.s_addr = inet_addr(multicastGroup.c_str());
|
||||
multicastRequest.imr_interface.s_addr = htonl(INADDR_ANY);
|
||||
if (setsockopt(sockDesc, IPPROTO_IP, IP_ADD_MEMBERSHIP,
|
||||
(raw_type *) &multicastRequest,
|
||||
sizeof(multicastRequest)) < 0) {
|
||||
throw SocketException("Multicast group join failed (setsockopt())", true);
|
||||
}
|
||||
multicastRequest.imr_multiaddr.s_addr = inet_addr(multicastGroup.c_str());
|
||||
multicastRequest.imr_interface.s_addr = htonl(INADDR_ANY);
|
||||
if (setsockopt(sockDesc, IPPROTO_IP, IP_ADD_MEMBERSHIP,
|
||||
(raw_type *) &multicastRequest,
|
||||
sizeof(multicastRequest)) < 0)
|
||||
{
|
||||
throw SocketException("Multicast group join failed (setsockopt())", true);
|
||||
}
|
||||
}
|
||||
|
||||
void UDPSocket::leaveGroup(const string &multicastGroup) {
|
||||
struct ip_mreq multicastRequest;
|
||||
void UDPSocket::leaveGroup(const string &multicastGroup)
|
||||
{
|
||||
struct ip_mreq multicastRequest;
|
||||
|
||||
multicastRequest.imr_multiaddr.s_addr = inet_addr(multicastGroup.c_str());
|
||||
multicastRequest.imr_interface.s_addr = htonl(INADDR_ANY);
|
||||
if (setsockopt(sockDesc, IPPROTO_IP, IP_DROP_MEMBERSHIP,
|
||||
(raw_type *) &multicastRequest,
|
||||
sizeof(multicastRequest)) < 0) {
|
||||
throw SocketException("Multicast group leave failed (setsockopt())", true);
|
||||
}
|
||||
multicastRequest.imr_multiaddr.s_addr = inet_addr(multicastGroup.c_str());
|
||||
multicastRequest.imr_interface.s_addr = htonl(INADDR_ANY);
|
||||
if (setsockopt(sockDesc, IPPROTO_IP, IP_DROP_MEMBERSHIP,
|
||||
(raw_type *) &multicastRequest,
|
||||
sizeof(multicastRequest)) < 0)
|
||||
{
|
||||
throw SocketException("Multicast group leave failed (setsockopt())", true);
|
||||
}
|
||||
}
|
||||
|
496
Socket.h
496
Socket.h
@ -9,320 +9,326 @@
|
||||
/**
|
||||
* Signals a problem with the execution of a socket call.
|
||||
*/
|
||||
class SocketException : public std::exception {
|
||||
class SocketException : public std::exception
|
||||
{
|
||||
public:
|
||||
/**
|
||||
* Construct a SocketException with a explanatory message.
|
||||
* @param message explanatory message
|
||||
* @param incSysMsg true if system message (from strerror(errno))
|
||||
* should be postfixed to the user provided message
|
||||
*/
|
||||
SocketException(const std::string &message, bool inclSysMsg = false) ;
|
||||
/**
|
||||
* Construct a SocketException with a explanatory message.
|
||||
* @param message explanatory message
|
||||
* @param incSysMsg true if system message (from strerror(errno))
|
||||
* should be postfixed to the user provided message
|
||||
*/
|
||||
SocketException(const std::string &message, bool inclSysMsg = false) ;
|
||||
|
||||
/**
|
||||
* Provided just to guarantee that no exceptions are thrown.
|
||||
*/
|
||||
~SocketException() noexcept (true);
|
||||
/**
|
||||
* Provided just to guarantee that no exceptions are thrown.
|
||||
*/
|
||||
~SocketException() noexcept (true);
|
||||
|
||||
/**
|
||||
* Get the exception message
|
||||
* @return exception message
|
||||
*/
|
||||
const char *what();
|
||||
/**
|
||||
* Get the exception message
|
||||
* @return exception message
|
||||
*/
|
||||
const char *what();
|
||||
|
||||
private:
|
||||
std::string userMessage; // Exception message
|
||||
std::string userMessage; // Exception message
|
||||
};
|
||||
|
||||
/**
|
||||
* Base class representing basic communication endpoint
|
||||
*/
|
||||
class Socket {
|
||||
class Socket
|
||||
{
|
||||
public:
|
||||
/**
|
||||
* Close and deallocate this socket
|
||||
*/
|
||||
~Socket();
|
||||
/**
|
||||
* Close and deallocate this socket
|
||||
*/
|
||||
~Socket();
|
||||
|
||||
/**
|
||||
* Get the local address
|
||||
* @return local address of socket
|
||||
* @exception SocketException thrown if fetch fails
|
||||
*/
|
||||
std::string getLocalAddress();
|
||||
/**
|
||||
* Get the local address
|
||||
* @return local address of socket
|
||||
* @exception SocketException thrown if fetch fails
|
||||
*/
|
||||
std::string getLocalAddress();
|
||||
|
||||
/**
|
||||
* Get the local port
|
||||
* @return local port of socket
|
||||
* @exception SocketException thrown if fetch fails
|
||||
*/
|
||||
unsigned short getLocalPort() ;
|
||||
/**
|
||||
* Get the local port
|
||||
* @return local port of socket
|
||||
* @exception SocketException thrown if fetch fails
|
||||
*/
|
||||
unsigned short getLocalPort() ;
|
||||
|
||||
/**
|
||||
* Set the local port to the specified port and the local address
|
||||
* to any interface
|
||||
* @param localPort local port
|
||||
* @exception SocketException thrown if setting local port fails
|
||||
*/
|
||||
void setLocalPort(unsigned short localPort) ;
|
||||
/**
|
||||
* Set the local port to the specified port and the local address
|
||||
* to any interface
|
||||
* @param localPort local port
|
||||
* @exception SocketException thrown if setting local port fails
|
||||
*/
|
||||
void setLocalPort(unsigned short localPort) ;
|
||||
|
||||
/**
|
||||
* Set the local port to the specified port and the local address
|
||||
* to the specified address. If you omit the port, a random port
|
||||
* will be selected.
|
||||
* @param localAddress local address
|
||||
* @param localPort local port
|
||||
* @exception SocketException thrown if setting local port or address fails
|
||||
*/
|
||||
void setLocalAddressAndPort(const std::string &localAddress,
|
||||
unsigned short localPort = 0) ;
|
||||
/**
|
||||
* Set the local port to the specified port and the local address
|
||||
* to the specified address. If you omit the port, a random port
|
||||
* will be selected.
|
||||
* @param localAddress local address
|
||||
* @param localPort local port
|
||||
* @exception SocketException thrown if setting local port or address fails
|
||||
*/
|
||||
void setLocalAddressAndPort(const std::string &localAddress,
|
||||
unsigned short localPort = 0) ;
|
||||
|
||||
/**
|
||||
* If WinSock, unload the WinSock DLLs; otherwise do nothing. We ignore
|
||||
* this in our sample client code but include it in the library for
|
||||
* completeness. If you are running on Windows and you are concerned
|
||||
* about DLL resource consumption, call this after you are done with all
|
||||
* Socket instances. If you execute this on Windows while some instance of
|
||||
* Socket exists, you are toast. For portability of client code, this is
|
||||
* an empty function on non-Windows platforms so you can always include it.
|
||||
* @param buffer buffer to receive the data
|
||||
* @param bufferLen maximum number of bytes to read into buffer
|
||||
* @return number of bytes read, 0 for EOF, and -1 for error
|
||||
* @exception SocketException thrown WinSock clean up fails
|
||||
*/
|
||||
static void cleanUp() ;
|
||||
/**
|
||||
* If WinSock, unload the WinSock DLLs; otherwise do nothing. We ignore
|
||||
* this in our sample client code but include it in the library for
|
||||
* completeness. If you are running on Windows and you are concerned
|
||||
* about DLL resource consumption, call this after you are done with all
|
||||
* Socket instances. If you execute this on Windows while some instance of
|
||||
* Socket exists, you are toast. For portability of client code, this is
|
||||
* an empty function on non-Windows platforms so you can always include it.
|
||||
* @param buffer buffer to receive the data
|
||||
* @param bufferLen maximum number of bytes to read into buffer
|
||||
* @return number of bytes read, 0 for EOF, and -1 for error
|
||||
* @exception SocketException thrown WinSock clean up fails
|
||||
*/
|
||||
static void cleanUp() ;
|
||||
|
||||
/**
|
||||
* Resolve the specified service for the specified protocol to the
|
||||
* corresponding port number in host byte order
|
||||
* @param service service to resolve (e.g., "http")
|
||||
* @param protocol protocol of service to resolve. Default is "tcp".
|
||||
*/
|
||||
static unsigned short resolveService(const std::string &service,
|
||||
const std::string &protocol = "tcp");
|
||||
|
||||
void setKeepalive();
|
||||
void setBlocking(bool flag);
|
||||
|
||||
int getFD();
|
||||
/**
|
||||
* Resolve the specified service for the specified protocol to the
|
||||
* corresponding port number in host byte order
|
||||
* @param service service to resolve (e.g., "http")
|
||||
* @param protocol protocol of service to resolve. Default is "tcp".
|
||||
*/
|
||||
static unsigned short resolveService(const std::string &service,
|
||||
const std::string &protocol = "tcp");
|
||||
|
||||
void setKeepalive();
|
||||
void setBlocking(bool flag);
|
||||
|
||||
int getFD();
|
||||
|
||||
private:
|
||||
// Prevent the user from trying to use value semantics on this object
|
||||
Socket(const Socket &sock);
|
||||
void operator=(const Socket &sock);
|
||||
// Prevent the user from trying to use value semantics on this object
|
||||
Socket(const Socket &sock);
|
||||
void operator=(const Socket &sock);
|
||||
|
||||
protected:
|
||||
int sockDesc; // Socket descriptor
|
||||
Socket(int type, int protocol) ;
|
||||
Socket(int sockDesc);
|
||||
int sockDesc; // Socket descriptor
|
||||
Socket(int type, int protocol) ;
|
||||
Socket(int sockDesc);
|
||||
};
|
||||
|
||||
/**
|
||||
* Socket which is able to connect, send, and receive
|
||||
*/
|
||||
class CommunicatingSocket : public Socket {
|
||||
class CommunicatingSocket : public Socket
|
||||
{
|
||||
public:
|
||||
/**
|
||||
* Establish a socket connection with the given foreign
|
||||
* address and port
|
||||
* @param foreignAddress foreign address (IP address or name)
|
||||
* @param foreignPort foreign port
|
||||
* @exception SocketException thrown if unable to establish connection
|
||||
*/
|
||||
void connect(const std::string &foreignAddress, unsigned short foreignPort)
|
||||
;
|
||||
/**
|
||||
* Establish a socket connection with the given foreign
|
||||
* address and port
|
||||
* @param foreignAddress foreign address (IP address or name)
|
||||
* @param foreignPort foreign port
|
||||
* @exception SocketException thrown if unable to establish connection
|
||||
*/
|
||||
void connect(const std::string &foreignAddress, unsigned short foreignPort)
|
||||
;
|
||||
|
||||
/**
|
||||
* Write the given buffer to this socket. Call connect() before
|
||||
* calling send()
|
||||
* @param buffer buffer to be written
|
||||
* @param bufferLen number of bytes from buffer to be written
|
||||
* @exception SocketException thrown if unable to send data
|
||||
*/
|
||||
void send(const void *buffer, int bufferLen) ;
|
||||
/**
|
||||
* Write the given buffer to this socket. Call connect() before
|
||||
* calling send()
|
||||
* @param buffer buffer to be written
|
||||
* @param bufferLen number of bytes from buffer to be written
|
||||
* @exception SocketException thrown if unable to send data
|
||||
*/
|
||||
void send(const void *buffer, int bufferLen) ;
|
||||
|
||||
/**
|
||||
* Read into the given buffer up to bufferLen bytes data from this
|
||||
* socket. Call connect() before calling recv()
|
||||
* @param buffer buffer to receive the data
|
||||
* @param bufferLen maximum number of bytes to read into buffer
|
||||
* @return number of bytes read, 0 for EOF, and -1 for error
|
||||
* @exception SocketException thrown if unable to receive data
|
||||
*/
|
||||
int recv(void *buffer, int bufferLen) ;
|
||||
/**
|
||||
* Read into the given buffer up to bufferLen bytes data from this
|
||||
* socket. Call connect() before calling recv()
|
||||
* @param buffer buffer to receive the data
|
||||
* @param bufferLen maximum number of bytes to read into buffer
|
||||
* @return number of bytes read, 0 for EOF, and -1 for error
|
||||
* @exception SocketException thrown if unable to receive data
|
||||
*/
|
||||
int recv(void *buffer, int bufferLen) ;
|
||||
|
||||
/**
|
||||
* Get the foreign address. Call connect() before calling recv()
|
||||
* @return foreign address
|
||||
* @exception SocketException thrown if unable to fetch foreign address
|
||||
*/
|
||||
std::string getForeignAddress() ;
|
||||
/**
|
||||
* Get the foreign address. Call connect() before calling recv()
|
||||
* @return foreign address
|
||||
* @exception SocketException thrown if unable to fetch foreign address
|
||||
*/
|
||||
std::string getForeignAddress() ;
|
||||
|
||||
/**
|
||||
* Get the foreign port. Call connect() before calling recv()
|
||||
* @return foreign port
|
||||
* @exception SocketException thrown if unable to fetch foreign port
|
||||
*/
|
||||
unsigned short getForeignPort() ;
|
||||
/**
|
||||
* Get the foreign port. Call connect() before calling recv()
|
||||
* @return foreign port
|
||||
* @exception SocketException thrown if unable to fetch foreign port
|
||||
*/
|
||||
unsigned short getForeignPort() ;
|
||||
|
||||
protected:
|
||||
CommunicatingSocket(int type, int protocol) ;
|
||||
CommunicatingSocket(int newConnSD);
|
||||
CommunicatingSocket(int type, int protocol) ;
|
||||
CommunicatingSocket(int newConnSD);
|
||||
};
|
||||
|
||||
/**
|
||||
* TCP socket for communication with other TCP sockets
|
||||
*/
|
||||
class TCPSocket : public CommunicatingSocket {
|
||||
class TCPSocket : public CommunicatingSocket
|
||||
{
|
||||
public:
|
||||
/**
|
||||
* Construct a TCP socket with no connection
|
||||
* @exception SocketException thrown if unable to create TCP socket
|
||||
*/
|
||||
TCPSocket() ;
|
||||
/**
|
||||
* Construct a TCP socket with no connection
|
||||
* @exception SocketException thrown if unable to create TCP socket
|
||||
*/
|
||||
TCPSocket() ;
|
||||
|
||||
/**
|
||||
* Construct a TCP socket with a connection to the given foreign address
|
||||
* and port
|
||||
* @param foreignAddress foreign address (IP address or name)
|
||||
* @param foreignPort foreign port
|
||||
* @exception SocketException thrown if unable to create TCP socket
|
||||
*/
|
||||
TCPSocket(const std::string &foreignAddress, unsigned short foreignPort, bool keepalive = false)
|
||||
;
|
||||
/**
|
||||
* Construct a TCP socket with a connection to the given foreign address
|
||||
* and port
|
||||
* @param foreignAddress foreign address (IP address or name)
|
||||
* @param foreignPort foreign port
|
||||
* @exception SocketException thrown if unable to create TCP socket
|
||||
*/
|
||||
TCPSocket(const std::string &foreignAddress, unsigned short foreignPort, bool keepalive = false)
|
||||
;
|
||||
|
||||
bool isOpen();
|
||||
|
||||
bool isOpen();
|
||||
|
||||
private:
|
||||
// Access for TCPServerSocket::accept() connection creation
|
||||
friend class TCPServerSocket;
|
||||
TCPSocket(int newConnSD);
|
||||
// Access for TCPServerSocket::accept() connection creation
|
||||
friend class TCPServerSocket;
|
||||
TCPSocket(int newConnSD);
|
||||
};
|
||||
|
||||
/**
|
||||
* TCP socket class for servers
|
||||
*/
|
||||
class TCPServerSocket : public Socket {
|
||||
class TCPServerSocket : public Socket
|
||||
{
|
||||
public:
|
||||
/**
|
||||
* Construct a TCP socket for use with a server, accepting connections
|
||||
* on the specified port on any interface
|
||||
* @param localPort local port of server socket, a value of zero will
|
||||
* give a system-assigned unused port
|
||||
* @param queueLen maximum queue length for outstanding
|
||||
* connection requests (default 5)
|
||||
* @exception SocketException thrown if unable to create TCP server socket
|
||||
*/
|
||||
TCPServerSocket(unsigned short localPort, int queueLen = 5, bool keepaliveIN = false);
|
||||
/**
|
||||
* Construct a TCP socket for use with a server, accepting connections
|
||||
* on the specified port on any interface
|
||||
* @param localPort local port of server socket, a value of zero will
|
||||
* give a system-assigned unused port
|
||||
* @param queueLen maximum queue length for outstanding
|
||||
* connection requests (default 5)
|
||||
* @exception SocketException thrown if unable to create TCP server socket
|
||||
*/
|
||||
TCPServerSocket(unsigned short localPort, int queueLen = 5, bool keepaliveIN = false);
|
||||
|
||||
/**
|
||||
* Construct a TCP socket for use with a server, accepting connections
|
||||
* on the specified port on the interface specified by the given address
|
||||
* @param localAddress local interface (address) of server socket
|
||||
* @param localPort local port of server socket
|
||||
* @param queueLen maximum queue length for outstanding
|
||||
* connection requests (default 5)
|
||||
* @exception SocketException thrown if unable to create TCP server socket
|
||||
*/
|
||||
TCPServerSocket(const std::string &localAddress, unsigned short localPort,
|
||||
int queueLen = 5, bool keepaliveIN = false);
|
||||
/**
|
||||
* Construct a TCP socket for use with a server, accepting connections
|
||||
* on the specified port on the interface specified by the given address
|
||||
* @param localAddress local interface (address) of server socket
|
||||
* @param localPort local port of server socket
|
||||
* @param queueLen maximum queue length for outstanding
|
||||
* connection requests (default 5)
|
||||
* @exception SocketException thrown if unable to create TCP server socket
|
||||
*/
|
||||
TCPServerSocket(const std::string &localAddress, unsigned short localPort,
|
||||
int queueLen = 5, bool keepaliveIN = false);
|
||||
|
||||
/**
|
||||
* Blocks until a new connection is established on this socket or error
|
||||
* @return new connection socket
|
||||
* @exception SocketException thrown if attempt to accept a new connection fails
|
||||
*/
|
||||
TCPSocket *accept() ;
|
||||
/**
|
||||
* Blocks until a new connection is established on this socket or error
|
||||
* @return new connection socket
|
||||
* @exception SocketException thrown if attempt to accept a new connection fails
|
||||
*/
|
||||
TCPSocket *accept() ;
|
||||
|
||||
|
||||
private:
|
||||
void setListen(int queueLen) ;
|
||||
bool keepalive;
|
||||
void setListen(int queueLen) ;
|
||||
bool keepalive;
|
||||
};
|
||||
|
||||
/**
|
||||
* UDP socket class
|
||||
*/
|
||||
class UDPSocket : public CommunicatingSocket {
|
||||
class UDPSocket : public CommunicatingSocket
|
||||
{
|
||||
public:
|
||||
/**
|
||||
* Construct a UDP socket
|
||||
* @exception SocketException thrown if unable to create UDP socket
|
||||
*/
|
||||
UDPSocket() ;
|
||||
/**
|
||||
* Construct a UDP socket
|
||||
* @exception SocketException thrown if unable to create UDP socket
|
||||
*/
|
||||
UDPSocket() ;
|
||||
|
||||
/**
|
||||
* Construct a UDP socket with the given local port
|
||||
* @param localPort local port
|
||||
* @exception SocketException thrown if unable to create UDP socket
|
||||
*/
|
||||
UDPSocket(unsigned short localPort) ;
|
||||
/**
|
||||
* Construct a UDP socket with the given local port
|
||||
* @param localPort local port
|
||||
* @exception SocketException thrown if unable to create UDP socket
|
||||
*/
|
||||
UDPSocket(unsigned short localPort) ;
|
||||
|
||||
/**
|
||||
* Construct a UDP socket with the given local port and address
|
||||
* @param localAddress local address
|
||||
* @param localPort local port
|
||||
* @exception SocketException thrown if unable to create UDP socket
|
||||
*/
|
||||
UDPSocket(const std::string &localAddress, unsigned short localPort)
|
||||
;
|
||||
/**
|
||||
* Construct a UDP socket with the given local port and address
|
||||
* @param localAddress local address
|
||||
* @param localPort local port
|
||||
* @exception SocketException thrown if unable to create UDP socket
|
||||
*/
|
||||
UDPSocket(const std::string &localAddress, unsigned short localPort)
|
||||
;
|
||||
|
||||
/**
|
||||
* Unset foreign address and port
|
||||
* @return true if disassociation is successful
|
||||
* @exception SocketException thrown if unable to disconnect UDP socket
|
||||
*/
|
||||
void disconnect() ;
|
||||
/**
|
||||
* Unset foreign address and port
|
||||
* @return true if disassociation is successful
|
||||
* @exception SocketException thrown if unable to disconnect UDP socket
|
||||
*/
|
||||
void disconnect() ;
|
||||
|
||||
/**
|
||||
* Send the given buffer as a UDP datagram to the
|
||||
* specified address/port
|
||||
* @param buffer buffer to be written
|
||||
* @param bufferLen number of bytes to write
|
||||
* @param foreignAddress address (IP address or name) to send to
|
||||
* @param foreignPort port number to send to
|
||||
* @return true if send is successful
|
||||
* @exception SocketException thrown if unable to send datagram
|
||||
*/
|
||||
void sendTo(const void *buffer, int bufferLen, const std::string &foreignAddress,
|
||||
unsigned short foreignPort) ;
|
||||
/**
|
||||
* Send the given buffer as a UDP datagram to the
|
||||
* specified address/port
|
||||
* @param buffer buffer to be written
|
||||
* @param bufferLen number of bytes to write
|
||||
* @param foreignAddress address (IP address or name) to send to
|
||||
* @param foreignPort port number to send to
|
||||
* @return true if send is successful
|
||||
* @exception SocketException thrown if unable to send datagram
|
||||
*/
|
||||
void sendTo(const void *buffer, int bufferLen, const std::string &foreignAddress,
|
||||
unsigned short foreignPort) ;
|
||||
|
||||
/**
|
||||
* Read read up to bufferLen bytes data from this socket. The given buffer
|
||||
* is where the data will be placed
|
||||
* @param buffer buffer to receive data
|
||||
* @param bufferLen maximum number of bytes to receive
|
||||
* @param sourceAddress address of datagram source
|
||||
* @param sourcePort port of data source
|
||||
* @return number of bytes received and -1 for error
|
||||
* @exception SocketException thrown if unable to receive datagram
|
||||
*/
|
||||
int recvFrom(void *buffer, int bufferLen, std::string &sourceAddress,
|
||||
unsigned short &sourcePort) ;
|
||||
/**
|
||||
* Read read up to bufferLen bytes data from this socket. The given buffer
|
||||
* is where the data will be placed
|
||||
* @param buffer buffer to receive data
|
||||
* @param bufferLen maximum number of bytes to receive
|
||||
* @param sourceAddress address of datagram source
|
||||
* @param sourcePort port of data source
|
||||
* @return number of bytes received and -1 for error
|
||||
* @exception SocketException thrown if unable to receive datagram
|
||||
*/
|
||||
int recvFrom(void *buffer, int bufferLen, std::string &sourceAddress,
|
||||
unsigned short &sourcePort) ;
|
||||
|
||||
/**
|
||||
* Set the multicast TTL
|
||||
* @param multicastTTL multicast TTL
|
||||
* @exception SocketException thrown if unable to set TTL
|
||||
*/
|
||||
void setMulticastTTL(unsigned char multicastTTL) ;
|
||||
/**
|
||||
* Set the multicast TTL
|
||||
* @param multicastTTL multicast TTL
|
||||
* @exception SocketException thrown if unable to set TTL
|
||||
*/
|
||||
void setMulticastTTL(unsigned char multicastTTL) ;
|
||||
|
||||
/**
|
||||
* Join the specified multicast group
|
||||
* @param multicastGroup multicast group address to join
|
||||
* @exception SocketException thrown if unable to join group
|
||||
*/
|
||||
void joinGroup(const std::string &multicastGroup) ;
|
||||
/**
|
||||
* Join the specified multicast group
|
||||
* @param multicastGroup multicast group address to join
|
||||
* @exception SocketException thrown if unable to join group
|
||||
*/
|
||||
void joinGroup(const std::string &multicastGroup) ;
|
||||
|
||||
/**
|
||||
* Leave the specified multicast group
|
||||
* @param multicastGroup multicast group address to leave
|
||||
* @exception SocketException thrown if unable to leave group
|
||||
*/
|
||||
void leaveGroup(const std::string &multicastGroup) ;
|
||||
/**
|
||||
* Leave the specified multicast group
|
||||
* @param multicastGroup multicast group address to leave
|
||||
* @exception SocketException thrown if unable to leave group
|
||||
*/
|
||||
void leaveGroup(const std::string &multicastGroup) ;
|
||||
|
||||
private:
|
||||
void setBroadcast();
|
||||
void setBroadcast();
|
||||
};
|
||||
|
||||
#endif
|
||||
|
125
clienthandler.h
125
clienthandler.h
@ -10,22 +10,22 @@
|
||||
class ClientHandler
|
||||
{
|
||||
private:
|
||||
bool _isBroadcasting = false;
|
||||
CommunicatingSocket *_socket;
|
||||
bool _disconnected = false;
|
||||
|
||||
bool _isBroadcasting = false;
|
||||
CommunicatingSocket *_socket;
|
||||
bool _disconnected = false;
|
||||
|
||||
public:
|
||||
|
||||
void cleanUp();
|
||||
ClientHandler(CommunicatingSocket * const socket);
|
||||
~ClientHandler();
|
||||
bool operator==(int fd);
|
||||
bool operator!=(int fd);
|
||||
|
||||
void cleanUp();
|
||||
ClientHandler(CommunicatingSocket * const socket);
|
||||
~ClientHandler();
|
||||
bool operator==(int fd);
|
||||
bool operator!=(int fd);
|
||||
bool operator==(ClientHandler& other);
|
||||
bool operator!=(ClientHandler& other);
|
||||
bool isDisconnected();
|
||||
bool run(std::vector<ClientHandler>* clients, int serial, bool verbose = false);
|
||||
void write(const char* buffer, const size_t len);
|
||||
bool operator!=(ClientHandler& other);
|
||||
bool isDisconnected();
|
||||
bool run(std::vector<ClientHandler>* clients, int serial, bool verbose = false);
|
||||
void write(const char* buffer, const size_t len);
|
||||
void dropData();
|
||||
};
|
||||
|
||||
@ -50,75 +50,86 @@ void ClientHandler::dropData()
|
||||
|
||||
bool ClientHandler::run(std::vector<ClientHandler>* clients, int serial, bool verbose)
|
||||
{
|
||||
std::array<char, 4096> buffer;
|
||||
std::array<char, 4096> buffer;
|
||||
int reclen = 0;
|
||||
try
|
||||
{
|
||||
try
|
||||
{
|
||||
reclen = _socket->recv(buffer.data(), 4096);
|
||||
if(verbose) std::cout<<"Recived "<<reclen<<" bytes\n";
|
||||
if(verbose)
|
||||
std::cout<<"Recived "<<reclen<<" bytes\n";
|
||||
}
|
||||
catch (SocketException &e)
|
||||
{
|
||||
std::cout<<e.what()<<std::endl;
|
||||
_disconnected = true;
|
||||
}
|
||||
if(reclen > 0)
|
||||
{
|
||||
if(!_isBroadcasting && reclen >= 5 && strncmp( buffer.data(), "bcst:", 5) == 0) _isBroadcasting = true;
|
||||
|
||||
if(_isBroadcasting)
|
||||
{
|
||||
if(verbose) std::cout<<"Boradcasting "<<reclen<<" bytes\n";
|
||||
for(ClientHandler& item : *clients) if(operator!=(item))item.write(buffer.data(), reclen);
|
||||
char* newline = std::find(buffer.begin(), buffer.end(), '\n');
|
||||
if(newline != std::end(buffer)) _isBroadcasting = false;
|
||||
}
|
||||
else
|
||||
{
|
||||
if(verbose) std::cout<<"wrote "<<reclen<<" bytes to serial\n";
|
||||
if(sWrite(serial, buffer.data(), reclen) < 0 && (errno != EAGAIN || errno != EWOULDBLOCK))
|
||||
{
|
||||
throw serialIoException(serial, errno);
|
||||
}
|
||||
}
|
||||
}
|
||||
else if(reclen == 0) _disconnected = true;
|
||||
return !_disconnected;
|
||||
catch (SocketException &e)
|
||||
{
|
||||
std::cout<<e.what()<<std::endl;
|
||||
_disconnected = true;
|
||||
}
|
||||
if(reclen > 0)
|
||||
{
|
||||
if(!_isBroadcasting && reclen >= 5 && strncmp( buffer.data(), "bcst:", 5) == 0)
|
||||
_isBroadcasting = true;
|
||||
|
||||
if(_isBroadcasting)
|
||||
{
|
||||
if(verbose)
|
||||
std::cout<<"Boradcasting "<<reclen<<" bytes\n";
|
||||
for(ClientHandler& item : *clients)
|
||||
if(operator!=(item))
|
||||
item.write(buffer.data(), reclen);
|
||||
char* newline = std::find(buffer.begin(), buffer.end(), '\n');
|
||||
if(newline != std::end(buffer))
|
||||
_isBroadcasting = false;
|
||||
}
|
||||
else
|
||||
{
|
||||
if(verbose)
|
||||
std::cout<<"wrote "<<reclen<<" bytes to serial\n";
|
||||
if(sWrite(serial, buffer.data(), reclen) < 0 && (errno != EAGAIN || errno != EWOULDBLOCK))
|
||||
{
|
||||
throw serialIoException(serial, errno);
|
||||
}
|
||||
}
|
||||
}
|
||||
else if(reclen == 0)
|
||||
_disconnected = true;
|
||||
return !_disconnected;
|
||||
}
|
||||
|
||||
bool ClientHandler::isDisconnected(){return _disconnected;}
|
||||
bool ClientHandler::isDisconnected()
|
||||
{
|
||||
return _disconnected;
|
||||
}
|
||||
|
||||
void ClientHandler::write(const char* buffer, const size_t len)
|
||||
{
|
||||
try
|
||||
{
|
||||
try
|
||||
{
|
||||
_socket->send(buffer, len);
|
||||
}
|
||||
catch (SocketException &e)
|
||||
{
|
||||
std::cout<<e.what()<<std::endl;
|
||||
_disconnected = true;
|
||||
}
|
||||
catch (SocketException &e)
|
||||
{
|
||||
std::cout<<e.what()<<std::endl;
|
||||
_disconnected = true;
|
||||
}
|
||||
}
|
||||
|
||||
bool ClientHandler::operator==(int fd)
|
||||
{
|
||||
return fd == _socket->getFD();
|
||||
return fd == _socket->getFD();
|
||||
}
|
||||
|
||||
|
||||
bool ClientHandler::operator!=(int fd)
|
||||
{
|
||||
return fd != _socket->getFD();
|
||||
return fd != _socket->getFD();
|
||||
}
|
||||
|
||||
bool ClientHandler::operator==(ClientHandler& other)
|
||||
{
|
||||
return _socket->getFD() == other._socket->getFD();
|
||||
return _socket->getFD() == other._socket->getFD();
|
||||
}
|
||||
|
||||
|
||||
bool ClientHandler::operator!=(ClientHandler& other)
|
||||
{
|
||||
return !(operator==(other));
|
||||
return !(operator==(other));
|
||||
}
|
||||
|
68
main.cpp
68
main.cpp
@ -20,7 +20,7 @@
|
||||
|
||||
sig_atomic_t stop = false;
|
||||
|
||||
void intHandler(int sig)
|
||||
void intHandler(int sig)
|
||||
{
|
||||
stop = true;
|
||||
}
|
||||
@ -60,18 +60,24 @@ static int parseCmdArgs(int argc, char** argv, Config *config)
|
||||
}
|
||||
else if (std::string(argv[i]) == "--serialport" || std::string(argv[i]) == "-p")
|
||||
{
|
||||
if(argc > i) config->portFileName = argv[i+1];
|
||||
else return -1;
|
||||
if(argc > i)
|
||||
config->portFileName = argv[i+1];
|
||||
else
|
||||
return -1;
|
||||
}
|
||||
else if (std::string(argv[i]) == "--port" || std::string(argv[i]) == "-P")
|
||||
{
|
||||
if(argc > i) config->port = atoi(argv[i+1]);
|
||||
else return -1;
|
||||
if(argc > i)
|
||||
config->port = atoi(argv[i+1]);
|
||||
else
|
||||
return -1;
|
||||
}
|
||||
else if (std::string(argv[i]) == "--baud" || std::string(argv[i]) == "-b")
|
||||
{
|
||||
if(argc > i) config->baud = atoi(argv[i+1]);
|
||||
else return -1;
|
||||
if(argc > i)
|
||||
config->baud = atoi(argv[i+1]);
|
||||
else
|
||||
return -1;
|
||||
}
|
||||
else if (std::string(argv[i]) == "--sinkless" || std::string(argv[i]) == "-s" )
|
||||
{
|
||||
@ -94,17 +100,18 @@ static int parseCmdArgs(int argc, char** argv, Config *config)
|
||||
return 0;
|
||||
}
|
||||
|
||||
void acceptThreadFunction( TCPServerSocket* servSock, std::vector<ClientHandler>* clients, std::mutex* clientsMutex, int pollQue )
|
||||
void acceptThreadFunction( TCPServerSocket* servSock, std::vector<ClientHandler>* clients, std::mutex* clientsMutex,
|
||||
int pollQue )
|
||||
{
|
||||
while(!stop)
|
||||
{
|
||||
while(!stop)
|
||||
{
|
||||
TCPSocket* newSock = servSock->accept();
|
||||
if(newSock != nullptr)
|
||||
{
|
||||
clientsMutex->lock();
|
||||
clients->push_back(ClientHandler(newSock)); // Wait for a client to connect
|
||||
struct epoll_event ev;
|
||||
ev.events = EPOLLIN;
|
||||
ev.events = EPOLLIN;
|
||||
ev.data.fd = newSock->getFD();
|
||||
clientsMutex->unlock();
|
||||
epoll_ctl(pollQue, EPOLL_CTL_ADD, newSock->getFD(), &ev);
|
||||
@ -123,11 +130,12 @@ int openSerialPort(const Config& config)
|
||||
{
|
||||
std::cout<<"Opeing serial port: "<<config.portFileName<<" at "<<config.baud<<" baud\n";
|
||||
serial = serialport_init(config.portFileName.c_str(), config.baud);
|
||||
if(serial == -1)
|
||||
if(serial == -1)
|
||||
std::cout<<"Opeing serial port failed\n";
|
||||
tcflush(serial, TCIOFLUSH);
|
||||
}
|
||||
else std::cout<<"Sinkless mode\n";
|
||||
else
|
||||
std::cout<<"Sinkless mode\n";
|
||||
return serial;
|
||||
}
|
||||
|
||||
@ -162,12 +170,12 @@ int serialPortReconnect(Config& config, std::string err)
|
||||
int main(int argc, char* argv[])
|
||||
{
|
||||
Config config;
|
||||
|
||||
|
||||
if(parseCmdArgs(argc, argv, &config) != 0)
|
||||
return -1;
|
||||
|
||||
|
||||
std::cout<<"UVOS serial mulitplexer "<<VERSION<<'\n';
|
||||
|
||||
|
||||
int pollQue = epoll_create1(0);
|
||||
|
||||
std::mutex clientsMutex;
|
||||
@ -180,23 +188,23 @@ int main(int argc, char* argv[])
|
||||
{
|
||||
return 1;
|
||||
}
|
||||
else
|
||||
else
|
||||
{
|
||||
struct epoll_event ev = {};
|
||||
ev.events = EPOLLIN;
|
||||
ev.events = EPOLLIN;
|
||||
ev.data.fd = -1;
|
||||
epoll_ctl(pollQue, EPOLL_CTL_ADD, serial, &ev);
|
||||
}
|
||||
tcflush(serial, TCIOFLUSH);
|
||||
}
|
||||
else
|
||||
else
|
||||
{
|
||||
std::cout<<"Sinkless mode\n";
|
||||
}
|
||||
|
||||
|
||||
std::thread* acceptThread;
|
||||
TCPServerSocket* servSock;
|
||||
|
||||
|
||||
std::cout<<"opening TCP socket on port "<<config.port<<'\n';
|
||||
try
|
||||
{
|
||||
@ -209,13 +217,13 @@ int main(int argc, char* argv[])
|
||||
std::cerr<<"Could not open port"<<std::endl;
|
||||
return 1;
|
||||
}
|
||||
|
||||
|
||||
signal(SIGINT, intHandler);
|
||||
signal(SIGTERM, intHandler);
|
||||
signal(SIGPIPE, SIG_IGN);
|
||||
|
||||
signal(SIGPIPE, SIG_IGN);
|
||||
|
||||
std::cout<<"starting loop\n";
|
||||
|
||||
|
||||
while(!stop)
|
||||
{
|
||||
struct epoll_event ev;
|
||||
@ -224,7 +232,7 @@ int main(int argc, char* argv[])
|
||||
if(ev.data.fd != -1)
|
||||
{
|
||||
std::vector<ClientHandler>::iterator client =
|
||||
std::find(clients.begin(), clients.end(), ev.data.fd);
|
||||
std::find(clients.begin(), clients.end(), ev.data.fd);
|
||||
if(client == clients.end())
|
||||
continue;
|
||||
clientsMutex.lock();
|
||||
@ -251,7 +259,7 @@ int main(int argc, char* argv[])
|
||||
epoll_ctl(pollQue, EPOLL_CTL_ADD, serial, &ev);
|
||||
}
|
||||
}
|
||||
if((ev.events & (EPOLLHUP | EPOLLERR)) || client->isDisconnected())
|
||||
if((ev.events & (EPOLLHUP | EPOLLERR)) || client->isDisconnected())
|
||||
{
|
||||
client->cleanUp();
|
||||
clients.erase(client);
|
||||
@ -263,7 +271,7 @@ int main(int argc, char* argv[])
|
||||
{
|
||||
char buffer[4096];
|
||||
ssize_t readlen = sRead(serial, buffer, 4096);
|
||||
if(readlen < 0 && (errno != EAGAIN || errno != EWOULDBLOCK))
|
||||
if(readlen < 0 && (errno != EAGAIN || errno != EWOULDBLOCK))
|
||||
{
|
||||
close(serial);
|
||||
serial = serialPortReconnect(config, strerror(errno));
|
||||
@ -291,7 +299,7 @@ int main(int argc, char* argv[])
|
||||
std::cout<<"\" to clients from serial\n";
|
||||
}
|
||||
clientsMutex.lock();
|
||||
for(ClientHandler& client : clients)
|
||||
for(ClientHandler& client : clients)
|
||||
{
|
||||
client.write(buffer, readlen);
|
||||
}
|
||||
@ -299,7 +307,7 @@ int main(int argc, char* argv[])
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
acceptThread->join();
|
||||
delete acceptThread;
|
||||
for(ClientHandler& client : clients)
|
||||
|
128
serial_io.cpp
128
serial_io.cpp
@ -2,44 +2,48 @@
|
||||
|
||||
ssize_t sWrite(int port, char string[], size_t length)
|
||||
{
|
||||
if(port != -1) return write(port, string, length);
|
||||
else return 0;
|
||||
if(port != -1)
|
||||
return write(port, string, length);
|
||||
else
|
||||
return 0;
|
||||
}
|
||||
|
||||
ssize_t sWrite(int port, const char string[], size_t length)
|
||||
{
|
||||
if(port != -1) return write(port, string, length);
|
||||
else return 0;
|
||||
if(port != -1)
|
||||
return write(port, string, length);
|
||||
else
|
||||
return 0;
|
||||
}
|
||||
|
||||
ssize_t sRead(int port, void *buf, size_t count)
|
||||
{
|
||||
return (port != -1) ? read(port, buf, count) : 0;
|
||||
return (port != -1) ? read(port, buf, count) : 0;
|
||||
}
|
||||
|
||||
#ifdef __cplusplus
|
||||
void printRates()
|
||||
{
|
||||
std::cout<<"Rates:\n"\
|
||||
<<"Unchanged 0\n" \
|
||||
<<"B50 "<<B50<<'\n'\
|
||||
<<"B75 "<<B75<<'\n'\
|
||||
<<"B110 "<<B110<<'\n'\
|
||||
<<"B134 "<<B134<<'\n'\
|
||||
<<"B150 "<<B150<<'\n'\
|
||||
<<"B200 "<<B200<<'\n'\
|
||||
<<"B300 "<<B300<<'\n'\
|
||||
<<"B600 "<<B600<<'\n'\
|
||||
<<"B1200 "<<B1200<<'\n'\
|
||||
<<"B1800 "<<B1800<<'\n'\
|
||||
<<"B2400 "<<B2400<<'\n'\
|
||||
<<"B4800 "<<B4800<<'\n'\
|
||||
<<"B9600 "<<B9600<<'\n'\
|
||||
<<"B19200 "<<B19200<<'\n'\
|
||||
<<"B38400 "<<B38400<<'\n'\
|
||||
<<"B57600 "<<B57600<<'\n'\
|
||||
<<"B115200 "<<B115200<<'\n'\
|
||||
<<"B230400 "<<B230400<<'\n';
|
||||
std::cout<<"Rates:\n"\
|
||||
<<"Unchanged 0\n" \
|
||||
<<"B50 "<<B50<<'\n'\
|
||||
<<"B75 "<<B75<<'\n'\
|
||||
<<"B110 "<<B110<<'\n'\
|
||||
<<"B134 "<<B134<<'\n'\
|
||||
<<"B150 "<<B150<<'\n'\
|
||||
<<"B200 "<<B200<<'\n'\
|
||||
<<"B300 "<<B300<<'\n'\
|
||||
<<"B600 "<<B600<<'\n'\
|
||||
<<"B1200 "<<B1200<<'\n'\
|
||||
<<"B1800 "<<B1800<<'\n'\
|
||||
<<"B2400 "<<B2400<<'\n'\
|
||||
<<"B4800 "<<B4800<<'\n'\
|
||||
<<"B9600 "<<B9600<<'\n'\
|
||||
<<"B19200 "<<B19200<<'\n'\
|
||||
<<"B38400 "<<B38400<<'\n'\
|
||||
<<"B57600 "<<B57600<<'\n'\
|
||||
<<"B115200 "<<B115200<<'\n'\
|
||||
<<"B230400 "<<B230400<<'\n';
|
||||
}
|
||||
#endif
|
||||
|
||||
@ -47,26 +51,26 @@ int serialport_set_config(int fd, int baud)
|
||||
{
|
||||
struct termios toptions;
|
||||
if (tcgetattr(fd, &toptions) < 0)
|
||||
{
|
||||
perror("init_serialport: Couldn't get term attributes");
|
||||
return -1;
|
||||
}
|
||||
// 8N1
|
||||
toptions.c_cflag &= ~PARENB;
|
||||
toptions.c_cflag &= ~CSTOPB;
|
||||
toptions.c_cflag &= ~CSIZE;
|
||||
toptions.c_cflag |= CS8;
|
||||
|
||||
// no flow control
|
||||
toptions.c_cflag &= ~(CRTSCTS | CLOCAL);
|
||||
{
|
||||
perror("init_serialport: Couldn't get term attributes");
|
||||
return -1;
|
||||
}
|
||||
// 8N1
|
||||
toptions.c_cflag &= ~PARENB;
|
||||
toptions.c_cflag &= ~CSTOPB;
|
||||
toptions.c_cflag &= ~CSIZE;
|
||||
toptions.c_cflag |= CS8;
|
||||
|
||||
// no flow control
|
||||
toptions.c_cflag &= ~(CRTSCTS | CLOCAL);
|
||||
|
||||
//Make Raw
|
||||
toptions.c_iflag &= ~(IGNBRK | BRKINT | PARMRK | ISTRIP | INLCR | IGNCR | ICRNL | IXON);
|
||||
toptions.c_oflag &= ~OPOST; //hmm examine
|
||||
toptions.c_lflag &= ~(ECHO | ECHONL | ICANON | ISIG | IEXTEN);
|
||||
toptions.c_cflag &= ~(CSIZE | PARENB);
|
||||
toptions.c_cflag |= CS8;
|
||||
|
||||
//Make Raw
|
||||
toptions.c_iflag &= ~(IGNBRK | BRKINT | PARMRK | ISTRIP | INLCR | IGNCR | ICRNL | IXON);
|
||||
toptions.c_oflag &= ~OPOST; //hmm examine
|
||||
toptions.c_lflag &= ~(ECHO | ECHONL | ICANON | ISIG | IEXTEN);
|
||||
toptions.c_cflag &= ~(CSIZE | PARENB);
|
||||
toptions.c_cflag |= CS8;
|
||||
|
||||
if(baud != 0)
|
||||
{
|
||||
int error = cfsetispeed(&toptions, baud) | cfsetospeed(&toptions, baud);
|
||||
@ -77,33 +81,33 @@ int serialport_set_config(int fd, int baud)
|
||||
return -1;
|
||||
}
|
||||
}
|
||||
// see: http://unixwiz.net/techtips/termios-vmin-vtime.html
|
||||
toptions.c_cc[VMIN] = 0;
|
||||
toptions.c_cc[VTIME] = 40;
|
||||
fcntl(fd, F_SETFL, FNDELAY);
|
||||
if( tcsetattr(fd, TCSANOW, &toptions) < 0)
|
||||
{
|
||||
perror("init_serialport: Couldn't set term attributes");
|
||||
return -1;
|
||||
}
|
||||
return 0;
|
||||
// see: http://unixwiz.net/techtips/termios-vmin-vtime.html
|
||||
toptions.c_cc[VMIN] = 0;
|
||||
toptions.c_cc[VTIME] = 40;
|
||||
fcntl(fd, F_SETFL, FNDELAY);
|
||||
if( tcsetattr(fd, TCSANOW, &toptions) < 0)
|
||||
{
|
||||
perror("init_serialport: Couldn't set term attributes");
|
||||
return -1;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
int serialport_init(const char* device, int baud, bool block)
|
||||
{
|
||||
int fd;
|
||||
fd = open(device, O_RDWR | O_NOCTTY | (block ? 0 : O_NONBLOCK));
|
||||
if (fd == -1)
|
||||
{
|
||||
int fd;
|
||||
fd = open(device, O_RDWR | O_NOCTTY | (block ? 0 : O_NONBLOCK));
|
||||
if (fd == -1)
|
||||
{
|
||||
perror("init_serialport: Unable to open port ");
|
||||
return -1;
|
||||
}
|
||||
|
||||
if(serialport_set_config(fd, baud) != 0)
|
||||
}
|
||||
|
||||
if(serialport_set_config(fd, baud) != 0)
|
||||
{
|
||||
close(fd);
|
||||
fd = -1;
|
||||
}
|
||||
return fd;
|
||||
return fd;
|
||||
}
|
||||
|
||||
|
13
serial_io.h
13
serial_io.h
@ -29,12 +29,13 @@ int serialport_init(const char* device, int baud = BAUDRATE, bool block = false)
|
||||
#ifdef __cplusplus
|
||||
class serialIoException: public std::runtime_error
|
||||
{
|
||||
public:
|
||||
int fd;
|
||||
int errorNumber;
|
||||
serialIoException(int fd_, int errorNumber_):
|
||||
std::runtime_error("file descriptor error, fd: " + std::to_string(fd_) + " error: " + strerror(errorNumber_) + "\n"), fd(fd_), errorNumber(errorNumber_)
|
||||
{}
|
||||
public:
|
||||
int fd;
|
||||
int errorNumber;
|
||||
serialIoException(int fd_, int errorNumber_):
|
||||
std::runtime_error("file descriptor error, fd: " + std::to_string(fd_) + " error: " + strerror(errorNumber_) + "\n"),
|
||||
fd(fd_), errorNumber(errorNumber_)
|
||||
{}
|
||||
};
|
||||
#endif
|
||||
|
||||
|
Loading…
x
Reference in New Issue
Block a user