Skip to content

Instantly share code, notes, and snippets.

@LouisJenkinsCS
Last active August 29, 2015 14:17
Show Gist options
  • Save LouisJenkinsCS/62eb616623f0dcb3cd66 to your computer and use it in GitHub Desktop.
Save LouisJenkinsCS/62eb616623f0dcb3cd66 to your computer and use it in GitHub Desktop.
#include <stddef.h>
#include <stdio.h>
#include <signal.h>
#include <errno.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <sys/un.h>
#include <unistd.h>
#include "client.h"
#define SOCK_PATH "Testing123"
#define BUF_SIZE 255
// Defined a new buffer size constant: BUF_SIZE
int create_connection(const char *filename){
int sock;
struct sockaddr_un *me;
size_t size;
fprintf(stderr, "Creating socket...\n");
sock = socket(AF_UNIX, SOCK_STREAM, 0);
if(sock < 0){
perror("Socket");
exit(EXIT_FAILURE);
}
fprintf(stderr, "Done!\n");
me->sun_family = AF_LOCAL;
strncpy(me->sun_path, filename, sizeof(me->sun_path));
size = offsetof(struct sockaddr_un, sun_path) + strlen(me->sun_path);
fprintf(stderr, "Attempting to connect to server...\n");
if(connect(sock, (struct sockaddr *) me, size)){
perror("Connection");
exit(EXIT_FAILURE);
}
fprintf(stderr, "Done!\n");
return sock;
}
void write_message(int socket, char * message){
int bytesWritten = write(socket, message, sizeof(char) * strlen(message));
if(bytesWritten < 0){
perror("Write");
}
}
void clean_up_client(int signal){
printf("Cleaning up...\n");
unlink(SOCK_PATH);
printf("Done!\n");
exit(EXIT_SUCCESS);
}
int init_client(const char *filepath){
signal(SIGQUIT, clean_up_client);
signal(SIGINT, clean_up_client);
signal(SIGTERM, clean_up_client);
return create_connection(filepath);
}
int close_client(int socket){
shutdown(socket, 2);
unlink(SOCK_PATH);
}
int main(){
int socket = init_client(SOCK_PATH);
printf("Client Initialized! Client value: %d\n", socket);
char *message = malloc(sizeof(char) * BUF_SIZE); // Fixed to allocate memory for the buffer
while(1){
memset(message, 0, sizeof(message));
printf("\nMessage:");
fgets(message, BUF_SIZE, stdin); // Reads up to the buffer size from the input stream.
write_message(socket, message);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment