IPV6_V6ONLY setsockopt added for the udp server.
#include <stdio.h> // Per l'I/O de stdin/stdout
#include <sys/socket.h> // Per les macros bool,true,false
#include <sys/un.h> // Per les estructures dels unix sockets
#include <errno.h> // Pels errors de les crides a fitxer
#include <string.h> // Per strerror()
#include <stdlib.h> // Per abort()
#include <assert.h> // Per assert()
#include <unistd.h> // Per les crides a fitxer
#include "rfc3164.h" // Per MESSAGE_LENGTH
void show_help(const char * restrict program)
{
printf("Usage: %s <unix_socket>\n", program);
}
int connect_unix(const char * restrict socketname)
{
int socket_unix;
struct sockaddr_un source_unix;
int result;
socket_unix = socket(PF_UNIX, SOCK_DGRAM, 0 );
if (socket_unix == -1)
{
printf("Unix socket creation error: %s\n", strerror(errno));
abort();
/* Unreachable */
return -1;
}
/* Unix socket listen address */
memset(&source_unix, 0, sizeof(source_unix));
source_unix.sun_family = AF_UNIX;
strcpy(source_unix.sun_path, socketname);
result = connect(socket_unix, (struct sockaddr *) &source_unix,
sizeof(source_unix));
if (result == -1)
{
printf("Unix socket connect error: %s\n", strerror(errno));
abort();
/* Unreachable */
return -1;
}
/* Here we should take care of the socket permissions */
return socket_unix;
}
void writer_loop(const char * restrict socketname)
{
int socket_unix;
int result;
char message[MESSAGE_LENGTH+1];
socket_unix = connect_unix(socketname);
while (fgets(message, MESSAGE_LENGTH, stdin) != NULL )
{
send(socket_unix, message, strlen(message), 0);
/* Strip the last \n */
if (strlen(message) > 1)
message[strlen(message)-1] = '\0';
/* Allow exiting the program */
if(!strcmp(message,"close"))
break;
}
result = close(socket_unix);
if (result == -1)
{
printf("Unix socket close error: %s\n", strerror(errno));
abort();
}
}
int main(int argn, char **argv)
{
/* Processem els parĂ metres d'entrada */
if (argn != 2) {
show_help(argv[0]);
return 2;
}
writer_loop(argv[1]);
return 0;
}