Using telnet in a C Program

2019-01-17 23:54发布

问题:

I am working on a robot automation project and I have run into a road block. To control the robot, one needs to connect with it wirelessly via telnet and send commands through the tcp/ip protocol. (ex. The 'Mabc' command moves it forward based on the left wheel speed (a), the right wheel speed (b) and time (c)). What I am trying to do is do some calculations in a C program and then send a message to the robot based on the value of the calculation.

How can send commands via tcp/ip protocol in a C program?

Thanks!

Erik

回答1:

You are looking for sockets. This is a comprehensive guide to socket programming in C. Telnet is also a well defined protocol, although I don't know if this robot would use telnet or not (it's extra processing overhead for a protocol that wouldn't have much added benefit for a robot control program). Telnet is covered in detail by RFC 854



回答2:

Expect would allow you to interact with external programs, but I am not aware of a C port of expect. Otherwise you would find a telnet library in C or write your own using socket programming.



回答3:

I would use libcurl: http://curl.haxx.se/libcurl/. It'll do what you want, and handle all the telnet goo that you really don't want to handle.



回答4:

Expect was designed to do exactly this - hold conversations with interactive programs. It's written in Tcl, extending the Tcl interpreter with various commands. Tcl is very easy to extend; it was designed to be an embedded scripting language right from the word go. The main C API uses argv-style constructs to pass parameters to Tcl commands and is very easy to use. The best guide to the C API is Ousterhout's original book and it took me one two-hour lab session to get my first embedded Tcl interpreter up and running.

As a bonus you also get a built-in Tcl interpereter, which you can use to add a scripting capability to your application. You'll probably find that quite a bit of it can be implemented in Tcl if you feel so inclined, so it will probably save you time overall.



回答5:

I would be:

  • writing some simple shell scripts containing the telnet interractions written as here documents.
  • using a .telnetrc file in your home directory to control aspects of your telnet session, e.g. crmod
  • calling the script using system calls.

This way your turnaround time to change your interractions with the robot won't involve having to recompile your programm all the time.

BTW This sounds like fun.

HTH.

cheers,

Rob