C ++ WinSock向telnet服务器发送命令

时间:2017-07-27 17:52:02

标签: c++ telnet winsock

所以我正在制作一个通过telnet连接的C ++程序。连接似乎正在工作,因为我从服务器获得输出。问题是我需要向telnet发送一个特定的命令。例如命令:

  

登录用户密码

只是通过send()发送它似乎没有做任何事情(或者我做错了什么,但看不到它)。 页面ftp://ftp.rfc-editor.org/in-notes/rfc854.txt上有一些信息,但我真的不明白。

有人可以告诉我一个例子并解释我该怎么做才能使它有效?尝试谷歌,但我并没有真正找到我想要的。我确实需要它发送两个命令。

这是我尝试过的(不是完整的代码):

int main() {
  int iR;
  std::string input;
  std::cout << "Telnet ip: ";
  std::getline(std::cin, input);
  std::cout << std::endl;

  u_long ip = 0;
  u_short port = DEFAULT_PORT;
  u_long * ptr = &ip

  const char * cptr = input.c_str();
  inet_pton(AF_INET, cptr, ptr);

  std::cout << "Telnet port: ";
  std::getline(std::cin, input);
  std::cout << std::endl;
  iR = std::stoi(input);
  if((iR > SHRT_MAX) || (iR < 0)) {
    std::cout << "Wrong port number, using default." << std::endl;
  }
  else {
    port = iR;
  }

  WSADATA wsaData;
  iR = WSAStartup(MAKEWORD(2, 2), &wsaData);
  if (iR != 0) { return 1; }
  SOCKET server = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
  if (server == INVALID_SOCKET) { WSACleanup(); return 1; }

  sockaddr_in addr;
  addr.sin_family = AF_INET;
  addr.sin_addr.s_addr = ip;
  addr.sin_port = htons(port);

  std::string user;
  std::string pass;
  std::cout << "Username: ";
  std::getline(std::cin, user);
  std::cout << std::endl; << "Password: ";
  std::getline(std::cin, pass);
  std::cout << std::endl;

  std::cout << "Connecting..." << std::endl;
  if ((connect(server, (SOCKADDR *)&addr, sizeof(addr))) == SOCKET_ERROR) {
    std::cout << "Couldn't connect. << std::endl;
    WSAcleanup();
    Sleep(2000);
    return 0;
  }

  int bRecv = 0;
  char buff[2048];

  bRecv = recv(server, buff, sizeof(buff), 0);
  if ((bRecv == SOCKET_ERROR) || (bRecv == 0)) {
    std::cout << "Disconnected from the server." << std::endl;
    WSACleanup();
    return 0;
  }

  buff[bRecv] = 0;
  // When it connects successfully, a message appears on the screen from server
  std::cout << buff << std::endl;

  memset(buff, 0, sizeof(buff));
  std::string command = "login ";
  command.append(user);
  command.append(" ");
  command.append(pass);

  cptr = login.c_str();
  strcpy_s(buff, cptr);

  iR = send(server, buff, (u_int)strlen(buff), 0);
  if (iR == SOCKET_ERROR) { std::cout << "Couldn't send data." << std::endl; WSACleanup(); return 0;
  while (true) {
    bRecv = recv(server, buff, sizeof(buff), 0);
    if ((bRecv == SOCKET_ERROR) || (bRecv === 0)) {
      std::cout << "Disconnected from the server." << std::endl;
      break;
    }
    buff[bRecv] = 0;
    std::cout << buff << std::endl;
  }
  WSACleanup();
  return 0;
}

我的意思是我希望我不是以错误的方式做这件事。我几乎是C ++中的佼佼者。

1 个答案:

答案 0 :(得分:1)

您没有在命令后发送换行符。

std::string command = "login ";
command.append(user);
command.append(" ");
command.append(pass);
command.append("\r\n"); // <-- add this

您也无需使用buff来保存命令,您可以直接发送command

iR = send(server, command.c_str(), (u_int) command.length(), 0);