Compare commits

...

4 Commits

2 changed files with 17 additions and 1 deletions

View File

@@ -56,6 +56,9 @@ public:
/* Returns socket identifier */ /* Returns socket identifier */
int getSockFD(); int getSockFD();
/* Returns whether or not the given socket is connected to a remote address */
bool has_remote_address();
/* This is a pure virtual function (AKA an abstract function). It's purpose /* This is a pure virtual function (AKA an abstract function). It's purpose
is to be redefined by the children classes (client and server). */ is to be redefined by the children classes (client and server). */
virtual int get_type() = 0; virtual int get_type() = 0;

View File

@@ -37,6 +37,13 @@ Sock::Sock(char protocol, const char* address, int port) {
this->address = std::string(address); this->address = std::string(address);
} }
/* This method returns whether or not the socket is connected to a remote address */
bool Sock::has_remote_address() {
struct sockaddr_storage addr;
socklen_t len = sizeof(addr);
return getpeername(this->sock_fd, (struct sockaddr*)&addr, &len) == 0;
}
/* This method sends the given data, through the 'other_sockt' variable.. Client /* This method sends the given data, through the 'other_sockt' variable.. Client
and server classes extend this method, by setting this variable to different values. and server classes extend this method, by setting this variable to different values.
This function needs more testing for TCP, as it focuses on UDP right now. */ This function needs more testing for TCP, as it focuses on UDP right now. */
@@ -48,7 +55,13 @@ void Sock::sendAll(std::string to_send) {
/* For UDP sockets */ /* For UDP sockets */
if (this->protocol == ES_UDP) { if (this->protocol == ES_UDP) {
if (sendto(this->sock_fd, to_send.data(), str_length, 0, (struct sockaddr *)dest, addrlen) == -1) { int retval;
if (this->has_remote_address()) {
retval = send(this->sock_fd, to_send.data(), str_length, 0);
} else {
retval = sendto(this->sock_fd, to_send.data(), str_length, 0, (struct sockaddr *)dest, addrlen);
}
if (retval == -1) {
throw errno; throw errno;
} }
} }