How can I get the telnet result using C / Objective C?

与世无争的帅哥 提交于 2019-12-12 22:05:24

问题


Here is a telnet site:

telnet://202.85.101.136:8604/

It is from Hong Kong public library, can I write some programme to get the string / result from the telnet service, and send the request from C / Objective C? thz u.


回答1:


If you have a telnet program already on your system, you can use it to do all the connection work for you. Here's a program for gnu/Linux that you can use as a starting point.

It uses popen to execute the system's telnet command. Then it just reads all data from the pipe (stdout if you just executed the telnet command by itself from the shell) and prints it. When there's no more data to read, it exits.

You can send data to the server by opening the pipe in rw mode instead of r and then writing like you would any other file. You could conditionally do stuff like scan your input for Username: and then send a username string too, for instance.

#include <stdio.h>
#include <stdlib.h>

int main(int argc, char *argv[])
{
        const char *cmd = "telnet 202.85.101.136 8604";
        char buffer[256];

        FILE *pipe = popen(cmd, "r");
        if( !pipe ) { perror("popen"); exit(-1); }

        while( fgets(buffer, sizeof(buffer), pipe) != NULL &&
               !feof(pipe) )
        {
                if( ferror(pipe) ) { perror("fgets"); break; }

                /* Here you do whatever you want with the data. */
                printf("%s", buffer);
        }

        pclose(pipe);

        return 0;
}

If you're using Windows, this link explains the alternative to popen.

There's also a program called Expect that can help you automate stuff like this.




回答2:


Sure its possible. Telnet is a pretty simple protocol, you simply need to open a TCP socket and connect it to that IP and Port. When you first connect, the telnet server will send some negotiation requests using the binary protocol defined in RFC854, to which your client is expected to respond. Once negotiation is completed you communicate by simply sending and receiving ASCII data, normally a line at a time.

For a simple "get some data from a host" telnet sessions where you aren't trying to have a real interactive session, it sometimes works to simply accept all the servers negotiation settings to avoid implementing the whole negotiation protocol. To do this, just look for the server to send you several 3-byte commands in the format of: 0xFF 0xFD xx, which is basically the server telling you "I want you to use option X", just respond to this with 0xFF 0xFB xx, which basically is just you agreeing to whatever the server is asking for. Then when you get passed negotiations, you just have to receive lines with a socket read and send commands with a socket write.



来源:https://stackoverflow.com/questions/2913707/how-can-i-get-the-telnet-result-using-c-objective-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!