openConnection

This commit is contained in:
elvis
2022-04-21 18:56:47 +02:00
parent 048b4e7f87
commit da707a09eb

View File

@ -1,5 +1,22 @@
#include <string.h>
#include <errno.h>
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/socket.h>
#include <sys/un.h>
#include <sys/time.h>
#include <api.h> #include <api.h>
#define SOCKNAMEMAX 256 // should be at least 108
// -----------------------------------------------------------------------------
/* variabili globali */
int fd_skt; // descriptor of the socket
char socketName[SOCKNAMEMAX] = ""; // name of the socket
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
@ -12,9 +29,53 @@
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
int openConnection(const char* sockname, int msec, const struct timespec abstime){ int openConnection(const char* sockname, int msec, const struct timespec abstime){
if(!sockname){
errno = EINVAL;
return -1;
}
struct sockaddr_un sa;
struct timespec ts;
ts.tv_sec = msec/1000;
ts.tv_nsec = (msec % 1000) * 1000000;
struct timeval t1, t2; // for gettimeofday
long long start, end; // to calculate the time elapsed
long long elapsedTime;
// select socket
strncpy(sa.sun_path, sockname, sizeof(sa.sun_path));
sa.sun_family = AF_UNIX;
if ((fd_skt = socket(AF_UNIX, SOCK_STREAM, 0)) == -1) {
errno = EINVAL;
perror("socket");
return -1;
}
if(gettimeofday(&t1, NULL) != 0) {
perror("gettimeofday");
return -1;
}
start = (long long) (t1.tv_sec * 1000000000 + t1.tv_usec * 1000);
while (connect(fd_skt, (struct sockaddr*) &sa, sizeof(sa)) == -1) {
gettimeofday(&t2, NULL);
end = (long long) t2.tv_sec * 1000000000 + t2.tv_usec * 1000;
elapsedTime = (end - start);
// return if more time has elapsed than allowed
if (elapsedTime > (abstime.tv_sec * 1000000000) + abstime.tv_nsec) {
errno = ETIMEDOUT;
return -1;
}
nanosleep(&ts, &ts);
}
strncpy(socketName, sockname, sizeof(socketName));
return 1; return 1;
} }