Search code examples
clinuxtcpesp8266netcat

Send a message to my microcontroller using Netcat - C language


I've searched a lot and wasn't able to figure out how to solve my question. I have an esp8266 12E configured to receive a message through TCP/IP and activate a door if the message sent have the right password. I have the following code:

system ("netcat 192.168.4.1 555");

After executing on terminal netcat is open, but I'm not able to figure out how to let my program write the password automatically. Tried:

system ("netcat 192.168.4.1 555");
printf("key");

It wasn't able to write something after calling the netcat command. And after my program send the key it is needed to close netcat, how to do it?

I hope that I could explain myself in english, and would be glad getting help to solve this simple problem.

*I'm coding using linux, and my app will run on a raspberry pi.


Solution

  • popen is your friend. It's similar to system, but returns a "file pointer" (in inverted commas!) which you can read/write from/to.

    Several examples of its use can be found online.

    Untested pseudo-example:

    fp = popen("nc 192.168.4.1 555", "w");
    if (fp == NULL) {
       /* Handle error */
       printf("Couldn't spawn nc\n");
       exit(1);
    }
    fprintf(fp, "key"); // write to netcat's STDIN
    pclose(fp);
    

    Alternatively you could open a network socket and read/write to the network directly yourself: i.e. http://www.cs.tau.ac.il/~eddiea/samples/IOMultiplexing/TCP-client.c.html