我想从 CMTS 检索调制解调器列表,我用 C 编写了一个 telnet 客户端,它正在执行此操作。 问题是有时我无法从 CMTS 获取所有数据。 (如果我减少'延迟'等待时间,我越不会得到所有数据。)
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);
最佳答案
看看这个Beej's Guide to Network Programming
建议在联网时使用 recv 和 send 函数。
recv 返回接收到的字节数,如果发生错误则返回 -1。当对等方执行有序关闭时,返回值将为 0。
关于c - 从 C 中的 telnet 套接字读取,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20147195/