I would like to retrieve modem list from the CMTS, and I wrote a telnet client in C, that is executing this. The problem is that sometimes I do not get all the data from the CMTS. (If I reduce the 'delay' waiting time, the more I do not get all the data.)
char buf[50000];
int nbytes, sock;
struct sockaddr_in cmts;
cmts.sin_family = AF_INET;
cmts.sin_port = htons( 23 );
cmts.sin_addr.s_addr = inet_addr("192.168.1.1");
sock = socket( PF_INET, SOCK_STREAM, 0 );
if ( sock < 0 ) {
perror("Socket creation error!");
exit (EXIT_FAILURE);
}
if ( connect( sock, (struct sockaddr *) &cmts, sizeof( cmts ) ) < 0 ) {
perror("Connect process error!");
exit (EXIT_FAILURE);
}
write( sock, "testuser\n", 9 );
write( sock, "testenapwd\n", 11 );
write( sock, "terminal length 0\n", 18 );
usleep( 100000 );
read( sock, buf, sizeof( buf ) );
usleep( 100000 );
write( sock, "show cable modem\n", 17 );
usleep( 100000 );
while ( 1 ) {
nbytes = 0;
ioctl( sock, FIONREAD, &nbytes );
if ( !nbytes ) { break; }
else {
memset( buf, 0, sizeof( buf ) );
nbytes = read( sock, buf, sizeof( buf ) -1 );
printf("%s", buf);
printf(">>>%d<<<\n", nbytes); // for debug
}
usleep( 300000 ); // delay
}
close( sock );
exit (EXIT_SUCCESS);
Take a look at this Beej's Guide to Network Programming
It's recommended to use the recv and send functions when it comes to networking.
recv returns the number of bytes received, or -1 if an error occurred. The return value will be 0 when the peer has performed an orderly shutdown.