← Esempi di programmazione · libnex
07_forward.c
Il file da solo · nel pacchetto libnex-dev: /usr/share/doc/libnex-dev/examples/
/*
-------------------------------------------------------------------------------------------------
_ ____ _ _____ ___ ___ _ _ ____ _____ ____ _ _ _____ ____ ___ _
/ \ | _ \ / \|_ _/ _ \ |_ _| \ | |/ ___| ____/ ___| \ | | ____| _ \|_ _| / \
/ _ \ | |_) | / _ \ | || | | | | || \| | | _| _|| | _| \| | _| | |_) || | / _ \
/ ___ \| _ < / ___ \| || |_| | | || |\ | |_| | |__| |_| | |\ | |___| _ < | | / ___ \
/_/ \_\_| \_\/_/ \_\_| \___/ |___|_| \_|\____|_____\____|_| \_|_____|_| \_\___/_/ \_\
-------------------------------------------------------------------------------------------------
Copyright (c) 2026 Arato Ingegneria. Tutti i diritti riservati.
Name : 07_forward.c
Author : Ing. Roberto arato
Version : 1.0.0
Copyright : Ing. Roberto arato (c) 2026
Description : Esempio 7 - connessione TCP a un servizio visto da un altro nodo (nex forward)
-------------------------------------------------------------------------------------------------
*/
/*
nex_forward_json chiede al nodo indicato di aprire una connessione TCP verso
host:porta, come la vede quel nodo ("localhost" = il nodo stesso): servizi raggiungibili
solo dall'interno di un nodo diventano usabili da qui, nel canale cifrato fra gli agent.
I byte del servizio arrivano come STDOUT, quelli verso il servizio si mandano con
nex_job_write. Qui si legge il saluto del server SSH del nodo.
Uso: ./07_forward NODO [PORTA] es. ./07_forward node-b 22
*/
#include <stdio.h>
#include <stdlib.h>
#include <nex.h>
int main(int argc, char **argv) {
if (argc < 2) { fprintf(stderr, "uso: %s NODO [PORTA]\n", argv[0]); return 2; }
int port = argc > 2 ? atoi(argv[2]) : 22;
nex_conn *nd = nex_open(NULL);
if (nd == NULL) { fprintf(stderr, "agent non raggiungibile\n"); return 1; }
char *req = nex_forward_json(argv[1], "localhost", port);
int err, ev, letto = 0;
nex_job *conn = nex_run(nd, req, &err);
nex_free(req);
char *data;
size_t len;
while (conn && nex_job_next(conn, &ev, &data, &len) == NEX_OK) {
if (ev == NEX_EV_STARTED) printf("collegato: %s\n", data);
if (ev == NEX_EV_ERROR) printf("rifiutato: %s\n", data);
if (ev == NEX_EV_STDOUT) {
printf("il servizio dice: %.*s", (int)len, data);
letto = 1;
}
nex_free(data);
if (letto) break; // basta il saluto: si chiude la connessione
}
nex_job_free(conn);
nex_close(nd);
return letto ? 0 : 1;
}