I'm trying to write a client program and a server program in which when the client connects to the server, the server sends a random string from a file back to it. Here is what I have so far (reading from file omitted):
server.c
#include <sys/socket.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <sys/types.h>
#include <signal.h>
int listfd;
int connfd;
int main(int argc, char *argv[]){
/*
* Create Sockets
*/
listfd = socket(AF_UNIX, SOCK_STREAM, 0);
if(listfd == -1)
exit(-1);
struct sockaddr saddr = {AF_UNIX, "server"};
socklen_t saddrlen = sizeof(struct sockaddr) + 6;
bind(listfd, &saddr, saddrlen);
listen(listfd, 10);
fflush(stdout);
printf("Running...\n");
/*
* Listen for connections
* and send random phrase on accept
*/
while(1){
connfd = accept(listfd, NULL, NULL);
int r = rand() % num_of_lines; //Pick random phrase/hint pair
write(connfd, phrases[r], strlen(phrases[r]));
close(connfd);
sleep(1);
}
exit(0);
}
client.c
#include <sys/socket.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <sys/types.h>
#include <sys/ioctl.h>
int main(int argc, char *argv[])
{
int sock;
int conn;
struct sockaddr saddr = {AF_UNIX, "server"};
socklen_t saddrlen = sizeof(struct sockaddr) + 6;
sock = socket(AF_UNIX, SOCK_STREAM, 0);
conn = connect(sock, &saddr, saddrlen);
char BUFF[1024];
read(sock, BUFF, 1024);
printf("%s", BUFF);
return 0;
}
My problem arises when I try to print in the client. I run the server, but when I run the client, it only prints garbage characters, and I'm not entirely sure what's causing this.
Any help would be much appreciated, thank you!
EDIT:
I figured out my problem. Because the server socket was bound to "server", which was also the name of the executable, this caused a lot of issues.
Renaming the sockaddr.sa_data field fixed my problem.