socket: refactored genericsocket a bit to make socketdescriptor readable

This commit is contained in:
maliakal_d 2018-08-08 14:47:07 +02:00
parent 147194e8af
commit e77cdb35dd

View File

@ -26,7 +26,7 @@
replaced the argument of send/receive data with void (to avoid too much casting or compiler errors/warnings)
added a function which really does not close the socket between send/receive (senddataonly, receivedataonly)
*/
*/
#include "ansi.h"
@ -71,19 +71,23 @@ using namespace std;
class genericSocket{
public:
public:
/**
Communication protocol
*/
enum communicationProtocol{
/** Communication protocol */
enum communicationProtocol{
TCP, /**< TCP/IP */
UDP /**< UDP */
};
};
genericSocket(const char* const host_ip_or_name, unsigned short int const port_number,
/**
* The constructor for a client
* @param host_ip_or_name hostname or ip of the client
* @param port_number port number to connect to
* @param p TCP or UDP
* @param ps a single packet size
*/
genericSocket(const char* const host_ip_or_name,
unsigned short int const port_number,
communicationProtocol p, int ps = DEFAULT_PACKET_SIZE) :
portno(port_number),
protocol(p),
@ -95,8 +99,7 @@ enum communicationProtocol{
nsent(0),
total_sent(0),// sender (client): where to? ip
header_packet_size(0),
actual_udp_socket_buffer_size(0)
{
actual_udp_socket_buffer_size(0) {
memset(&serverAddress, 0, sizeof(serverAddress));
memset(&clientAddress, 0, sizeof(clientAddress));
memset(lastClientIP,0,INET_ADDRSTRLEN);
@ -107,43 +110,23 @@ enum communicationProtocol{
struct addrinfo *result;
if (!ConvertHostnameToInternetAddress(host_ip_or_name, &result)) {
serverAddress.sin_family = result->ai_family;
memcpy((char *) &serverAddress.sin_addr.s_addr, &((struct sockaddr_in *) result->ai_addr)->sin_addr, sizeof(in_addr_t));
memcpy((char *) &serverAddress.sin_addr.s_addr,
&((struct sockaddr_in *) result->ai_addr)->sin_addr, sizeof(in_addr_t));
freeaddrinfo(result);
serverAddress.sin_port = htons(port_number);
socketDescriptor=0;
}
clientAddress_length=sizeof(clientAddress);
}
int getProtocol(communicationProtocol p) {
switch (p) {
case TCP:
return SOCK_STREAM;
break;
case UDP:
return SOCK_DGRAM;
default:
cprintf(RED, "unknown protocol %d\n", p);
return -1;
}
}
int getProtocol() {return getProtocol(protocol);};
};
/**
The constructor for a server
@short the contructor for a server
\param port_number port number to listen to
\param p TCP or UDP
\param eth interface name or IP address to listen to (if NULL, listen to all interfaces)
* The constructor for a server
* throws an exception if
* @param port_number port number to connect to
* @param p TCP or UDP
* @param ps a single packet size
* @param eth interface name or IP address to listen to (if NULL, listen to all interfaces)
*/
genericSocket(unsigned short int const port_number, communicationProtocol p,
int ps = DEFAULT_PACKET_SIZE, const char *eth=NULL, int hsize=0,
uint32_t buf_size=SOCKET_BUFFER_SIZE):
@ -157,23 +140,17 @@ enum communicationProtocol{
nsent(0),
total_sent(0),
header_packet_size(hsize),
actual_udp_socket_buffer_size(0)
{
actual_udp_socket_buffer_size(0) {
memset(&serverAddress, 0, sizeof(serverAddress));
memset(&clientAddress, 0, sizeof(clientAddress));
/* // you can specify an IP address: */
/* // or you can let it automatically select one: */
/* myaddr.sin_addr.s_addr = INADDR_ANY; */
memset(lastClientIP,0,INET_ADDRSTRLEN);
memset(thisClientIP,0,INET_ADDRSTRLEN);
memset(dummyClientIP,0,INET_ADDRSTRLEN);
differentClients = 0;
// same port
if(serverAddress.sin_port == htons(port_number)){
socketDescriptor = -10;
return;
@ -189,9 +166,6 @@ enum communicationProtocol{
strcpy(ip,eth);
}
// strcpy(hostname,"localhost"); //needed?!?!?!?
socketDescriptor = socket(AF_INET, getProtocol(),0); //tcp
if (socketDescriptor < 0) {
@ -215,7 +189,8 @@ enum communicationProtocol{
// reuse port
{
int val=1;
if (setsockopt(socketDescriptor,SOL_SOCKET,SO_REUSEADDR,&val,sizeof(int)) == -1) {
if (setsockopt(socketDescriptor,SOL_SOCKET,SO_REUSEADDR,
&val,sizeof(int)) == -1) {
cprintf(RED, "setsockopt REUSEADDR failed\n");
socketDescriptor=-1;
return;
@ -231,35 +206,45 @@ enum communicationProtocol{
// confirm if sufficient
if (getsockopt(socketDescriptor, SOL_SOCKET, SO_RCVBUF, &ret_size, &optlen) == -1) {
FILE_LOG(logWARNING) << "[Port " << port_number << "] Could not get rx socket receive buffer size";
FILE_LOG(logWARNING) << "[Port " << port_number << "] "
"Could not get rx socket receive buffer size";
} else if (ret_size >= real_size) {
actual_udp_socket_buffer_size = ret_size;
#ifdef VEBOSE
FILE_LOG(logINFO) << "[Port " << port_number << "] UDP rx socket buffer size is sufficient (" << ret_size << ")";
FILE_LOG(logINFO) << "[Port " << port_number << "] "
"UDP rx socket buffer size is sufficient (" << ret_size << ")";
#endif
}
// not sufficient, enhance size
else {
// set buffer size (could not set)
if (setsockopt(socketDescriptor, SOL_SOCKET, SO_RCVBUF, &desired_size, optlen) == -1) {
FILE_LOG(logWARNING) << "[Port " << port_number << "] Could not set rx socket buffer size to "
if (setsockopt(socketDescriptor, SOL_SOCKET, SO_RCVBUF,
&desired_size, optlen) == -1) {
FILE_LOG(logWARNING) << "[Port " << port_number << "] "
"Could not set rx socket buffer size to "
<< desired_size << ". (No Root Privileges?)";
}
// confirm size
else if (getsockopt(socketDescriptor, SOL_SOCKET, SO_RCVBUF, &ret_size, &optlen) == -1) {
FILE_LOG(logWARNING) << "[Port " << port_number << "] Could not get rx socket buffer size";
else if (getsockopt(socketDescriptor, SOL_SOCKET, SO_RCVBUF,
&ret_size, &optlen) == -1) {
FILE_LOG(logWARNING) << "[Port " << port_number << "] "
"Could not get rx socket buffer size";
}
else if (ret_size >= real_size) {
actual_udp_socket_buffer_size = ret_size;
FILE_LOG(logINFO) << "[Port " << port_number << "] UDP rx socket buffer size modified to " << ret_size;
FILE_LOG(logINFO) << "[Port " << port_number << "] "
"UDP rx socket buffer size modified to " << ret_size;
}
// buffer size too large
else {
actual_udp_socket_buffer_size = ret_size;
// force a value larger than system limit (if run in a privileged context (capability CAP_NET_ADMIN set))
int ret = setsockopt(socketDescriptor, SOL_SOCKET, SO_RCVBUFFORCE, &desired_size, optlen);
getsockopt(socketDescriptor, SOL_SOCKET, SO_RCVBUF, &ret_size, &optlen);
// force a value larger than system limit
// (if run in a privileged context (capability CAP_NET_ADMIN set))
int ret = setsockopt(socketDescriptor, SOL_SOCKET, SO_RCVBUFFORCE,
&desired_size, optlen);
getsockopt(socketDescriptor, SOL_SOCKET, SO_RCVBUF,
&ret_size, &optlen);
if (ret == -1) {
FILE_LOG(logWARNING) << "[Port " << port_number << "] "
"Could not force rx socket buffer size to "
@ -268,7 +253,8 @@ enum communicationProtocol{
" To remove this warning: set rx_udpsocksize from client to <= " <<
(ret_size/2) << " (Real size:" << ret_size << ").";
} else {
FILE_LOG(logINFO) << "[Port " << port_number << "] UDP rx socket buffer size modified to " << ret_size;
FILE_LOG(logINFO) << "[Port " << port_number << "] "
"UDP rx socket buffer size modified to " << ret_size;
}
}
}
@ -287,78 +273,115 @@ enum communicationProtocol{
}
/**
* The destructor: disconnects and close the socket
*/
~genericSocket() {
Disconnect();
CloseServerTCPSocketDescriptor();
serverAddress.sin_port=-1;
};
/**
* Returns actual udp socket buffer size/2.
* Halving is because of kernel book keeping
* @returns actual udp socket buffer size/2
*/
int getActualUDPSocketBufferSize(){
return actual_udp_socket_buffer_size;
}
int getActualUDPSocketBufferSize(){return actual_udp_socket_buffer_size;};
/**
The destructor: disconnects and close the socket
@short the destructor
*/
~genericSocket(){ \
Disconnect();
if (socketDescriptor >= 0){ \
close(socketDescriptor); \
} \
if(is_a_server and getProtocol() == TCP){\
if(file_des>0)\
close(file_des);\
}
file_des=-1; \
serverAddress.sin_port=-1; \
};
/* /\** @short if client returns hostname for connection */
/* \param name string to write the hostname to */
/* \returns 0 if client, 1 if server (in this case ignore name return value) */
/* *\/ */
/* int getHostname(char *name){ */
/* if (is_a_server==0) { */
/* strcpy(name,getHostname().c_str()); */
/* } */
/* return is_a_server; */
/* }; */
/* /\** @short if client returns hostname for connection */
/* \returns hostname */
/* *\/ */
/* string getHostname(){return string(hostname);}; */
/* /\** @short returns port number for connection */
/* \returns port number */
/* *\/ */
/* int getPortNumber(){return portno;}; */
/** @short returns communication protocol
\returns TCP or UDP
* Get protocol TCP or UDP
- * @returns TCP or UDP
*/
int getCommunicationProtocol(){return protocol;};
/** @short returns error status
\returns 1 if error
/**
* Get port number
* @retrns port number
*/
int getErrorStatus(){if (socketDescriptor==-10) return -10; else if (socketDescriptor<0) return 1; else return 0;};
uint16_t getPortNumber(){return ntohs(serverAddress.sin_port);}
/**
* Get TCP Server File Descriptor
* @returns TCP Server file descriptor
*/
int getFileDes(){return file_des;};
/** @short etablishes connection; disconnect should always follow
\returns 1 if error
/**
* Get socket descriptor
* @returns socket descriptor
*/
int getsocketDescriptor(){return socketDescriptor;};
/**
* Get total bytes sent/received
* Makes sense only for udp socket as there is only receive data
*/
int getCurrentTotalReceived(){return total_sent;};
/**
* Get type of protocol based on protocol
* @param p TCP or UDP
* @returns SOCK_STREAM/SOCK_DGRAM or -1
*/
int getProtocol(communicationProtocol p) {
switch (p) {
case TCP:
return SOCK_STREAM;
break;
case UDP:
return SOCK_DGRAM;
default:
cprintf(RED, "unknown protocol %d\n", p);
return -1;
}
};
/**
* Get current protocol type
* @returns SOCK_STREAM/SOCK_DGRAM or -1
*/
int getProtocol() {return getProtocol(protocol);};
/**
* Get error status
* @returns 1 if error
*/
int getErrorStatus(){if (socketDescriptor==-10) return -10;
else if (socketDescriptor<0) return 1; else return 0;};
/**
* Close TCP Server socket descriptor
*/
void CloseServerTCPSocketDescriptor() {
if (getProtocol() == TCP && is_a_server) {
if (socketDescriptor >= 0) {
close(socketDescriptor);
socketDescriptor = -1;
}
}
};
/**
* Disconnect
*/
void Disconnect(){
if (protocol == TCP && is_a_server) {
if (file_des >= 0) {
close(file_des);
file_des = -1;
}
return;
}
if (socketDescriptor >= 0) {
close(socketDescriptor);
socketDescriptor = -1;
}
};
/**
* Establishes connection
* @returns 1 if error
*/
int Connect(){
@ -415,119 +438,87 @@ enum communicationProtocol{
default:
printf("unknown error\n");
}
socketDescriptor=-1;
}
else{
inet_ntop(AF_INET, &(clientAddress.sin_addr), dummyClientIP, INET_ADDRSTRLEN);
#ifdef VERY_VERBOSE
cout << "client connected "<< file_des << endl;
#endif
}
}
// file_des = socketDescriptor;
#ifdef VERY_VERBOSE
cout << "fd " << file_des << endl;
#endif
return file_des;
} else {
if (socketDescriptor<=0)
socketDescriptor = socket(AF_INET, getProtocol(),0);
// SetTimeOut(10);
if (socketDescriptor < 0){
cprintf(RED, "Can not create socket\n");
file_des = socketDescriptor;
} else {
if(connect(socketDescriptor,(struct sockaddr *) &serverAddress,sizeof(serverAddress))<0){
cprintf(RED, "Can not connect to socket\n");
file_des = -1;
} else{
file_des = socketDescriptor;
return -1;
}
}
}
return file_des;
}
uint16_t getPortNumber(){
return ntohs(serverAddress.sin_port);
}
int getFileDes(){return file_des;};
int getsocketDescriptor(){return socketDescriptor;};
void exitServer(){
if(is_a_server){
if (socketDescriptor>=0){
close(socketDescriptor);
socketDescriptor = -1;
}
}
}
/** @short free connection */
void Disconnect(){
if (protocol==UDP){
close(socketDescriptor);
socketDescriptor=-1;
}
else{
if(file_des>=0){ //then was open
if(is_a_server){
close(file_des);
}
else {
//while(!shutdown(socketDescriptor, SHUT_RDWR));
close(socketDescriptor);
socketDescriptor=-1;
}
file_des=-1;
}
return socketDescriptor;
}
};
/**
* Exit server
*/
void exitServer(){
Disconnect();
CloseServerTCPSocketDescriptor();
};
/**
* Shut down socket
*/
void ShutDownSocket(){
shutdown(socketDescriptor, SHUT_RDWR);
Disconnect();
};
/** Set the socket timeout ts is in seconds */
/**
* Set the socket timeout ts is in seconds
* @param ts time in seconds
* @returns 0 for success, else -1
*/
int SetTimeOut(int ts){
if (ts<=0)
return -1;
struct timeval tout;
tout.tv_sec = 0;
tout.tv_usec = 0;
if(::setsockopt(socketDescriptor, SOL_SOCKET, SO_RCVTIMEO, &tout, sizeof(struct timeval)) <0)
{
if(::setsockopt(socketDescriptor, SOL_SOCKET, SO_RCVTIMEO,
&tout, sizeof(struct timeval)) <0) {
cprintf(RED, "Error in setsockopt SO_RCVTIMEO %d\n", 0);
}
tout.tv_sec = ts;
tout.tv_usec = 0;
if(::setsockopt(socketDescriptor, SOL_SOCKET, SO_SNDTIMEO, &tout, sizeof(struct timeval)) < 0)
{
if(::setsockopt(socketDescriptor, SOL_SOCKET, SO_SNDTIMEO,
&tout, sizeof(struct timeval)) < 0) {
cprintf(RED, "Error in setsockopt SO_SNDTIMEO %d\n", ts);
}
return 0;
};
/**
* Set packet size
* @param i packet size
* @returns current packet size
*/
int setPacketSize(int i=-1) { if (i>=0) packet_size=i;return packet_size;};
/**
* Convert IP to hostname
* @param ip IP
* @returns hostname
*/
static string ipToName(string ip) {
struct ifaddrs *addrs, *iap;
struct sockaddr_in *sa;
@ -553,6 +544,11 @@ enum communicationProtocol{
return string(buf);
};
/**
* Convert interface to mac address
* @param inf interface
* @returns mac address
*/
static string nameToMac(string inf) {
struct ifreq ifr;
int sock, j, k;
@ -579,8 +575,11 @@ enum communicationProtocol{
};
/**
* Convert hostname to ip
* @param inf hostname
* @returns IP
*/
static string nameToIp(string inf){
struct ifreq ifr;
int sock;
@ -605,6 +604,12 @@ enum communicationProtocol{
};
/**
* Get socket
* @param inf hostname
* @param ifr interface request structure
* @returns sock
*/
static int getSock(string inf, struct ifreq *ifr) {
int sock;
@ -617,10 +622,8 @@ enum communicationProtocol{
ifr->ifr_name[sizeof(ifr->ifr_name)-1]='\0';
return sock;
};
/**
* Convert Hostname to Internet address info structure
* One must use freeaddrinfo(res) after using it
@ -670,20 +673,26 @@ enum communicationProtocol{
return 1;
}
/**
* Receive data only
* @param buf data
* @param length size of data expecting, 0 for a single packet
* @returns size of data received
*/
int ReceiveDataOnly(void* buf,int length=0){
if (buf==NULL) return -1;
total_sent=0;
int tcpfd = socketDescriptor;
switch(protocol) {
case TCP:
if (file_des<0) return -1;
tcpfd = (is_a_server ? file_des : socketDescriptor);
if (tcpfd<0) return -1;
while(length>0){
nsending = (length>packet_size) ? packet_size:length;
nsent = read(file_des,(char*)buf+total_sent,nsending);
nsent = read(tcpfd,(char*)buf+total_sent,nsending);
if(!nsent) {
if(!total_sent) {
return -1; //to handle it
@ -747,15 +756,15 @@ enum communicationProtocol{
#ifdef VERY_VERBOSE
cout << "sent "<< total_sent << " Bytes" << endl;
#endif
return total_sent;
}
/**
* Send data only
* @param buf data
* @param length size of data expecting
* @returns size of data sent
*/
int SendDataOnly(void *buf, int length) {
#ifdef VERY_VERBOSE
cout << "want to send "<< length << " Bytes" << endl;
@ -764,13 +773,15 @@ enum communicationProtocol{
total_sent=0;
int tcpfd = socketDescriptor;
switch(protocol) {
case TCP:
if (file_des<0) return -1;
tcpfd = (is_a_server ? file_des : socketDescriptor);
if (tcpfd<0) return -1;
while(length>0){
nsending = (length>packet_size) ? packet_size:length;
nsent = write(file_des,(char*)buf+total_sent,nsending);
nsent = write(tcpfd,(char*)buf+total_sent,nsending);
if(is_a_server && nsent < 0) {
cprintf(BG_RED, "Error writing to socket. Possible client socket crash\n");
break;
@ -800,18 +811,11 @@ enum communicationProtocol{
return total_sent;
}
int getCurrentTotalReceived(){
return total_sent;
}
char lastClientIP[INET_ADDRSTRLEN];
char thisClientIP[INET_ADDRSTRLEN];
int differentClients;
protected:
protected:
int portno;
communicationProtocol protocol;
int is_a_server;
@ -822,14 +826,10 @@ enum communicationProtocol{
socklen_t clientAddress_length;
char dummyClientIP[INET_ADDRSTRLEN];
private:
private:
int nsending;
int nsent;
int total_sent;
int header_packet_size;
int actual_udp_socket_buffer_size;
// pthread_mutex_t mp;
};