C
Summary - Socket programming
Combine socket, bind and accept to write an echo server.
Echo server
In this group you learned the basics of socket programming: create with socket, bind with bind, listen with listen, accept with accept, connect with connect and exchange data with send/recv.
Now you will combine them into an echo server: the server accepts a connection, receives data from the client and sends it back. The client sends, the server echoes and the client prints. This is the skeleton of real-world servers.
Exercise Write an echo server
Create a socket, bind, listen. Fork a child as client: connect, send(cfd, "echo", 4, 0), recv(cfd, cbuf, 4, 0). Parent server: accept, recv(client_fd, buf, 4, 0), send(client_fd, buf, 4, 0), printf("%s\n", buf). Use path /tmp/cb_e.sock.
Show example solution
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <sys/un.h>
#include <unistd.h>
#include <sys/wait.h>
int main(void) {
int listen_fd = socket(AF_UNIX, SOCK_STREAM, 0);
struct sockaddr_un addr;
memset(&addr, 0, sizeof(addr));
addr.sun_family = AF_UNIX;
strncpy(addr.sun_path, "/tmp/cb_e.sock", sizeof(addr.sun_path) - 1);
unlink("/tmp/cb_e.sock");
bind(listen_fd, (struct sockaddr *)&addr, sizeof(addr));
listen(listen_fd, 1);
pid_t pid = fork();
if (pid == 0) {
int cfd = socket(AF_UNIX, SOCK_STREAM, 0);
connect(cfd, (struct sockaddr *)&addr, sizeof(addr));
send(cfd, "echo", 4, 0);
char cbuf[16];
memset(cbuf, 0, sizeof(cbuf));
recv(cfd, cbuf, 4, 0);
close(cfd);
_exit(0);
}
int client_fd = accept(listen_fd, NULL, NULL);
char buf[16];
memset(buf, 0, sizeof(buf));
recv(client_fd, buf, 4, 0);
send(client_fd, buf, 4, 0);
printf("%s\n", buf);
close(client_fd);
close(listen_fd);
unlink("/tmp/cb_e.sock");
wait(NULL);
return 0;
}
Next steps
You learned socket programming. These foundations are the core of network servers, clients and inter-process communication.
Server and client can run on separate machines; with AF_INET you use an IP address and port. Combined with threads, you create a thread for each client. For multiple connections you use select or poll. The read and write calls you learned are the same here.
Test yourself
-
What sequence does an echo server follow?
- connect, send, recv
- accept, recv, send
- send, recv, connect
- recv, accept, send
Show answer
accept, recv, send — Server: accept, recv, send (echoes back).
-
Match server steps
- socket
- Create socket
- bind
- Bind to address
- listen
- Listen
- accept
- Accept connection
Next lesson: Pipe