In my ongoing attempts to become a better blog writer I have some written some more code that needs reviewing.
Full Source: https://github.com/Loki-Astari/Examples/tree/master/Version1
First Article: https://lokiastari.com/posts/SocketProgramminginC
This is a Simple Client Server implementation using RAW Sockets.
MakeFile
all: client server
clean:
rm -f *.o client server
CFLAGS = -Wall -Wextra -pedantic -Werror
client: client.o
server: server.o
client.cpp
#include <arpa/inet.h>
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#define CLIENT_BUFFER_SIZE 1024
int main(int argc, char* argv[])
{
if (argc != 3)
{
fprintf(stderr, "Usage: client <host> <Message>\n");
exit(1);
}
int socketId = socket(PF_INET, SOCK_STREAM, 0);
struct sockaddr_in serverAddr;
socklen_t addrSize = sizeof(serverAddr);
bzero((char*)&serverAddr, sizeof(serverAddr));
serverAddr.sin_family = AF_INET;
serverAddr.sin_port = htons(8080);
serverAddr.sin_addr.s_addr = inet_addr(argv[1]);
connect(socketId, (struct sockaddr*)&serverAddr, addrSize);
write(socketId, argv[2], strlen(argv[2]));
shutdown(socketId, SHUT_WR);
char buffer[CLIENT_BUFFER_SIZE];
size_t get = read(socketId, buffer, CLIENT_BUFFER_SIZE - 1);
buffer[get] = '\0';
fprintf(stdout, "%s %s\n", "Response from server", buffer);
close(socketId);
}
server.cpp
#include <netinet/in.h>
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#define SERVER_BUFFER_SIZE 1024
int main()
{
int socketId = socket(PF_INET, SOCK_STREAM, 0);
struct sockaddr_in serverAddr;
bzero((char*)&serverAddr, sizeof(serverAddr));
serverAddr.sin_family = AF_INET;
serverAddr.sin_port = htons(8080);
serverAddr.sin_addr.s_addr = INADDR_ANY;
bind(socketId, (struct sockaddr *) &serverAddr, sizeof(serverAddr));
listen(socketId, 5);
int finished = 0;
while(!finished)
{
struct sockaddr_storage serverStorage;
socklen_t addr_size = sizeof serverStorage;
int newSocket = accept(socketId, (struct sockaddr*)&serverStorage, &addr_size);
char buffer[SERVER_BUFFER_SIZE];
int get = read(newSocket, buffer, SERVER_BUFFER_SIZE - 1);
buffer[get] = '\0';
fprintf(stdout, "%s\n", buffer);
write(newSocket, "OK", 2);
fprintf(stdout, "Message Complete\n");
close(newSocket);
}
close(socketId);
}
libevent
. But before I get there I want to implement a threaded version (then show the event driven version to show that it is better). \$\endgroup\$