receiving from remote server giving junk characters?

1

I am trying to write a telnet client to connect to following server:

198.182.241.14 (hosted by: Pittsburg State University, Kansas, USA) - login: library

I have successfully connected through following code;

sd = socket(AF_INET, SOCK_STREAM, 0);
struct sockaddr_in sin;
memcpy(&sin.sin_addr.s_addr, host->h_addr, host->h_length);
sin.sin_family = AF_INET;
sin.sin_port = htons(portno);
if (connect(sd, (struct sockaddr *)&sin, sizeof(sin)) < 0)
{
    printf("error .. connecting sockets\n");
    return bRet;
}
printf("connected...\n");

Then I am sending "library" as password (As I understand I have to enter password hard coded )

But On receive, I am getting some junk characters:, and on next receive it got hanged:

char buf[2048] = {0};
send(sd, command, strlen(command),0);
send(sd, (void*)"\n",2,0);

Here command is "library"

This sending 7 bytes but, after that my exception is to receive some data from server:

**PSU Library Consortium - Select the Library to Search 1. PSU Axe Library Catalog ...... and more*

I am receiving through following code:

while(1)
{
    memset(buf, 0, 2048);
    int rv = recv(sd , buf , 2048 , 0);
    printf("received %d\n",rv);
    if (rv < 0)
        return false;
    else if (rv == 0) {
        printf("Connection closed by the remote end\n\r");
        return 0;
    }
    buf[rv] = '\0';
    printf("%s\n",buf);
    for(int i =0;i<strlen(buf);i++)
    {
        printf("%c = %d = 0x%08x\n",buf[i], buf[i], buf[i]);
    }
}

This is printing some junk characters as follow:

ÿýÿý ÿý#ÿý'
ÿ = -1 = 0xffffffff
ý = -3 = 0xfffffffd
 = 24 = 0x00000018
ÿ = -1 = 0xffffffff
ý = -3 = 0xfffffffd
  = 32 = 0x00000020
ÿ = -1 = 0xffffffff
ý = -3 = 0xfffffffd
# = 35 = 0x00000023
ÿ = -1 = 0xffffffff
ý = -3 = 0xfffffffd
' = 39 = 0x00000027
received 0
Connection closed by the remote end

Any Help?

More Edit: Any Good Article/Book ref/ Complete Code sample - so that I can start with socket programming and successfully login telnet servers through password

Thanks a lot in Advance

c++
c
linux
telnet
asked on Stack Overflow Jun 10, 2014 by (unknown user) • edited Jun 11, 2014 by (unknown user)

1 Answer

2

When you are connecting to a telnet server you must comply to the telnet protocol. While a telnet connection might look like a plain text send/receive, it really is an extra protocol. Every time you receive an 0xff this is a telnet escape code. Some cases:

  • 0xff 0xff = escape for 0xff data byte
  • 0xff 0xfd = DO, followed by the option code

So in your case the server sends you a DO(TerminalType=0x18), DO(TerminalSpeed=0x20), DO(XDisplayLocation0x23) and DO(NewEnvironmentOption=0x27). You should respond with WILL(...) or WONT(...). In any case to get the real data you have to filter out the telnet protocol parts.

Here are some interesting links for you:

answered on Stack Overflow Jun 11, 2014 by Werner Henze

User contributions licensed under CC BY-SA 3.0