views:

266

answers:

2

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.

+2  A: 

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.

bdk
+2  A: 

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.

indiv
The question is tagged Objective-C so the chances are it's not Windows. Or the tag is incorrectly applied.
JeremyP