Funny story, 7 years ago, I accidentally built RCE(remove code execution protocol) between systemverilog and Matlab. The project died long time ago but still one the most fun project i have worked on. At the time, I started with a simple TCP client/server implementation and build binary parsers above it. Anyway,This post is about that simple TCP client/server sockets.
Posix sockets is the de-facto standard for network stack implementation. It evolved from BSD sockets (more details in wiki). and it’s supported with modern operating systems(windows API has it’s quirks, DAMN YOU MS)
The minimal example is based on post.
client Link to heading
#include <stdio.h>
#include <string.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#define BUFSIZE 1000
#define PORT 2000
#define IP "127.0.0.1"
int main(void)
{
int sock;
struct sockaddr_in serv_address;
char buffer[BUFSIZE];
// create a socket
sock = socket(AF_INET, SOCK_STREAM, 0);
// con
serv_address.sin_family = AF_INET;
serv_address.sin_port = htons(PORT);
serv_address.sin_addr.s_addr = inet_addr(IP);
connect(sock, (struct sockaddr*)&serv_address, sizeof(serv_address));
strcpy(buffer , "hello");
send(sock, buffer, strlen(buffer), 0);
close(sock);
}
server Link to heading
#include <stdio.h>
#include <string.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#define BUFSIZE 1000
#define PORT 2000
#define IP "127.0.0.1"
int main(void)
{
int sock, client_sock, client_size;
struct sockaddr_in server_addr, client_addr;
char buffer[BUFSIZE];
sock = socket(AF_INET, SOCK_STREAM, 0);
server_addr.sin_family = AF_INET;
server_addr.sin_port = htons(PORT);
server_addr.sin_addr.s_addr = inet_addr(IP);
bind(sock, (struct sockaddr*)&server_addr, sizeof(server_addr));
listen(sock, 1);
client_size = sizeof(client_addr);
client_sock = accept(sock, (struct sockaddr*)&client_addr, &client_size);
recv(client_sock, buffer, sizeof(buffer), 0);
printf("Msg from client: %s\n", buffer);
close(client_sock);
close(sock);
return 0;
}