Skip to content

Commit

Permalink
Teach "pigs" to use the Unix socket
Browse files Browse the repository at this point in the history
  • Loading branch information
root authored and smurfix committed Dec 5, 2023
1 parent 9710fd9 commit 88c18b1
Showing 1 changed file with 44 additions and 21 deletions.
65 changes: 44 additions & 21 deletions pigs.c
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@ This version is for pigpio version 69+
#include <unistd.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <sys/un.h>
#include <netdb.h>
#include <arpa/inet.h>

Expand Down Expand Up @@ -109,40 +110,62 @@ static int initOpts(int argc, char *argv[])

static int openSocket(void)
{
int sock, err;
struct addrinfo hints, *res, *rp;
const char *addrStr, *portStr;
int sock;
const char *sockStr;

portStr = getenv(PI_ENVPORT);
sockStr = getenv(PI_ENVSOCK);
if (sockStr && *sockStr)
{
struct sockaddr_un addr;
addr.sun_family = AF_LOCAL;
strncpy (addr.sun_path, sockStr, sizeof (addr.sun_path));
addr.sun_path[sizeof (addr.sun_path) - 1] = 0;
sock = socket (AF_LOCAL, SOCK_STREAM, 0);
if (sock > -1)
{
if (connect (sock, (struct sockaddr *) &addr, sizeof (addr)) == -1)
{
close(sock);
sock = -1;
}
}
}
else
{
int err;
struct addrinfo hints, *res, *rp;
const char *addrStr, *portStr;

if (!portStr) portStr = PI_DEFAULT_SOCKET_PORT_STR;
portStr = getenv(PI_ENVPORT);

addrStr = getenv(PI_ENVADDR);
if (!portStr) portStr = PI_DEFAULT_SOCKET_PORT_STR;

if (!addrStr) addrStr = PI_DEFAULT_SOCKET_ADDR_STR;
addrStr = getenv(PI_ENVADDR);

memset (&hints, 0, sizeof (hints));
if (!addrStr) addrStr = PI_DEFAULT_SOCKET_ADDR_STR;

hints.ai_family = PF_UNSPEC;
hints.ai_socktype = SOCK_STREAM;
hints.ai_flags |= AI_CANONNAME;
memset (&hints, 0, sizeof (hints));

err = getaddrinfo(addrStr, portStr, &hints, &res);
hints.ai_family = PF_UNSPEC;
hints.ai_socktype = SOCK_STREAM;
hints.ai_flags |= AI_CANONNAME;

if (err) return SOCKET_OPEN_FAILED;
err = getaddrinfo(addrStr, portStr, &hints, &res);

for (rp=res; rp!=NULL; rp=rp->ai_next)
{
sock = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol);
if (err) return SOCKET_OPEN_FAILED;

if (sock == -1) continue;
for (rp=res; rp!=NULL; rp=rp->ai_next)
{
sock = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol);

if (connect(sock, rp->ai_addr, rp->ai_addrlen) != -1) break;
}
if (sock == -1) continue;

freeaddrinfo(res);
if (connect(sock, rp->ai_addr, rp->ai_addrlen) != -1) break;
}

if (rp == NULL) return SOCKET_OPEN_FAILED;
freeaddrinfo(res);
if (rp == NULL) return SOCKET_OPEN_FAILED;
}

return sock;
}
Expand Down

0 comments on commit 88c18b1

Please sign in to comment.