C program for client-server UNIX domain socket
/**************************************************************
* server.c
***************************************************************/
#include <stdio.h>
#include <unistd.h>
#include <sys/socket.h>
#include <sys/un.h>
#include <stdlib.h>
#define CLIENT_SOCK_FILE
"/home/labuser/unix_domain_socket/client_n"
#define SERVER_SOCK_FILE
"/home/labuser/unix_domain_socket/server_n"
struct msg {
char a[10];
char b[10];
char c[10];
};
int main(int argc, char
*argv[])
{
int fd;
struct
sockaddr_un addr;
char buff[512];
struct
sockaddr_un from;
int len;
socklen_t fromlen
= sizeof(from);
struct msg
sent_message;
memset(&sent_message,
'\0', sizeof(sent_message));
/* create
dispatcher socket */
if ((fd =
socket(PF_UNIX, SOCK_DGRAM, 0)) < 0) {
perror("socket");
exit(1);
}
memset(&addr,
0, sizeof(addr));
addr.sun_family =
AF_UNIX;
strcpy(addr.sun_path,
SERVER_SOCK_FILE);
unlink(SERVER_SOCK_FILE);
if (bind(fd,
(struct sockaddr *)&addr, sizeof(addr)) < 0) {
perror("bind");
exit(1);
}
memset(buff,
'\0', sizeof(buff));
/* Receive
Message from process Client */
while ((len =
recvfrom(fd, &sent_message, sizeof(sent_message)+1, 0, (struct sockaddr
*)&from, &fromlen)) > 0)
{
buff[len] = '\0';
/*
Foward the received message from process Client to PCD server */
fprintf(stderr, "message received %s\n", sent_message.a);
fprintf(stderr, "message received %s\n", sent_message.b);
fprintf(stderr, "message received %s\n", sent_message.c);
}
if (fd >= 0) {
close(fd);
}
return 0;
}
/**************************************************************
* client.c
***************************************************************/
#include <sys/socket.h>
#include <sys/un.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#define CLIENT_SOCK_FILE
"/home/labuser/unix_domain_socket/client_n"
#define SERVER_SOCK_FILE
"/home/labuser/unix_domain_socket/server_n"
struct msg {
char a[10];
char b[10];
char c[10];
};
int main(int argc, char *argv[]) {
int fd;
struct sockaddr_un addr;
int ret = 0;
struct msg sent_message;
memset(&sent_message, '\0',
sizeof(sent_message));
strcpy(sent_message.a, "abc");
strcpy(sent_message.b, "def");
strcpy(sent_message.c, "ghi");
if ((fd = socket(PF_UNIX, SOCK_DGRAM, 0)) < 0) {
ret = -1;
perror("socket");
return ret;
}
memset(&addr, 0, sizeof(addr));
addr.sun_family = AF_UNIX;
strcpy(addr.sun_path, CLIENT_SOCK_FILE);
unlink(CLIENT_SOCK_FILE);
if (bind(fd, (struct sockaddr *)&addr,
sizeof(addr)) < 0) {
ret = -1;
perror("bind");
close(fd);
return ret;
}
memset(&addr, 0, sizeof(addr));
addr.sun_family = AF_UNIX;
strcpy(addr.sun_path, SERVER_SOCK_FILE);
if (connect(fd, (struct sockaddr *)&addr,
sizeof(addr)) < 0) {
ret = -1;
perror("connect");
close(fd);
return ret;
}
//if (send(fd, message, strlen(message)+1, 0) <
0) {
if (send(fd, &sent_message,
sizeof(sent_message)+1, 0) < 0) {
ret = -1;
perror("send");
close(fd);
return ret;
}
close(fd);
return 0;
}