exemple minimal compilable

This commit is contained in:
tTh 2023-07-14 16:09:53 +02:00
parent 97909fdcd4
commit 07ae0d5a8a
4 changed files with 109 additions and 0 deletions

1
code/network/.gitignore vendored Normal file
View File

@ -0,0 +1 @@
emc-tnetd

12
code/network/Makefile Normal file
View File

@ -0,0 +1,12 @@
#
# NETWORK EXPERIMENTS
#
COPT = -Wall -DDEBUG_LEVEL=1 -pthread
# --------------------------------------------------
# Experimental Specialized Telnet Server
# (Exemple Minimal Compilable)
emc-tnetd: emc-tnetd.c Makefile
gcc $< $(COPT) -o $@

15
code/network/README.md Normal file
View File

@ -0,0 +1,15 @@
= Network / Réseau
Some experiments on network programming.
== Telnet server
Une étude pour pouvoir intégrer un accès "console" à n'importe quelle
application. La première ébauche a rapidement permis de comprendre
que c'est pas si simple que ça.
Le fichier `emc-tnetd.c` a mis en évidence deux soucis.
Sauras-tu les trouver ?

81
code/network/emc-tnetd.c Normal file
View File

@ -0,0 +1,81 @@
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#define TL 20
int main(int argc, char *argv[])
{
int foo, len, sock;
char *adr_ip = "127.0.0.1";
int port = 5678;
unsigned int addrlen;
int connected;
struct sockaddr_in addr;
struct in_addr ia;
FILE *fpin;
char line[TL+5], *ptr;
fprintf(stderr, "--- %s ---\n", argv[0]);
sock = socket(AF_INET, SOCK_STREAM, 0);
if (sock < 0) {
perror(__FILE__ " start socket");
return -1;
}
#define S sizeof(struct sockaddr_in)
memset(&addr, 0, S);
addr.sin_family = AF_INET;
addr.sin_port = htons(port);
if (adr_ip && inet_aton(adr_ip, &ia)) {
addr.sin_addr = ia;
fprintf(stderr, "attached to %s\n", adr_ip);
}
if ((foo=bind(sock, (struct sockaddr *)&addr, S)) < 0) {
perror(__FILE__ " fail on bind ");
close(sock);
return -2;
}
fprintf(stderr, "bind -> %d\n", foo);
foo = listen(sock, 5); /* 5 is a bsd magic number */
if (foo) {
perror(__FILE__ " no magic in listen ");
return -3;
}
/* start of the endless loop */
for (;;) {
fprintf(stderr, "accepting...\n");
addrlen = sizeof(struct sockaddr);
connected = accept(sock, (struct sockaddr *)&addr, &addrlen);
if (connected < 0) {
perror(__FILE__ " accept");
return -1;
}
fprintf(stderr, "accept -> %d\n", connected);
if (NULL==(fpin = fdopen(connected, "r+"))) {
perror(__FILE__ " fdopen on connected");
return -3;
}
// fprintf(stderr, "fopened...\n");
while ( (ptr=fgets(line, TL, fpin)) ) {
len = strlen(line);
fprintf(stderr, " %3d | %s", len, line);
for (foo=0; foo<len; foo++) {
fprintf(fpin, "%02X ", (unsigned char)line[foo]);
}
fputs("\n", fpin);
}
close(connected);
} /* end of the endless loop */
return 0;
}