Skip to content

Instantly share code, notes, and snippets.

@vastus
Created January 17, 2025 02:01
Show Gist options
  • Save vastus/25b7f35e80398aee5217c8c9da0eb8a9 to your computer and use it in GitHub Desktop.
Save vastus/25b7f35e80398aee5217c8c9da0eb8a9 to your computer and use it in GitHub Desktop.
// $ make simple && ./simple &
// $ telnet localhost 6969
#include <netdb.h>
#include <netinet/in.h>
#include <stdio.h>
#include <stdlib.h>
#include <strings.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <unistd.h>
unsigned char buf[BUFSIZ];
int handleConn(int conn);
int main(void)
{
// socket
int sock = socket(PF_INET, SOCK_STREAM, 0);
if (sock < 0) {
perror("socket");
exit(1);
}
// (address)
struct sockaddr_in name = {
.sin_family = AF_INET,
.sin_port = htons(6969),
.sin_addr = { .s_addr = INADDR_ANY },
};
// bind
if (bind(sock, (const struct sockaddr *)&name, sizeof name) < 0) {
perror("bind");
exit(1);
}
// listen
if (listen(sock, 1) < 0) {
perror("listen");
exit(1);
}
// accept
for (;;) {
int conn = accept(sock, 0, 0);
if (conn < 0) {
perror("accept");
exit(1);
}
handleConn(conn);
}
return 0;
}
int handleConn(int conn)
{
int nread = 0;
int nwritten = 0;
printf("handleConn() conn=%d\n", conn);
while (nread = read(conn, buf, BUFSIZ), nread > 0) {
buf[nread] = '\0';
printf("nread=%d buf=%s\n", nread, buf);
nwritten = write(STDOUT_FILENO, buf, nread);
if (nwritten < 0) {
perror("write");
return -2;
}
nwritten = write(conn, buf, nread);
if (nwritten < 0) {
perror("write");
return -2;
}
}
if (nread < 0) {
perror("read");
return -1;
}
printf("closing conn=%d\n", conn);
if (close(conn) < 0) {
perror("close");
exit(1);
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment