Serwer echa w C++ sockety i połączenie telnet

0

Napisałem taki serwer echa w C++ działającym pod Linuksem:

#include <iostream>
#include <cstdlib>
#include <cctype>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h> // struct sockaddr_in
#include <unistd.h>

using namespace std;

/*
 *  Simple echo server: toupper.
 */

#define PORT 1000

int main()
{
  int sockfd, newsockfd;
  sockaddr_in server = {AF_INET, PORT, INADDR_ANY};
  pid_t pid;
  
  if( (sockfd = socket(AF_INET, SOCK_STREAM, 0)) == -1 ) {
    cerr << "Socket call failed" << endl;
    exit(1);
  }
  
  // bind socket with server address
  if( bind(sockfd, (sockaddr*) &server, sizeof(sockaddr_in)) == -1 ) {
    cerr << "bind call failed" << endl;
    exit(1);
  }
  
  // start listen
  if( listen(sockfd, 5) == -1 ) {
    cerr << "listen call failed" << endl;
    exit(1);
  }
  
  // start accept loop
  char c;
  for(; ;) {
    if( (newsockfd = accept(sockfd, NULL, NULL)) == -1) {
      cerr << "accept call failed" << endl;
      continue;
    }
    
    // create child for new connection
    switch(pid = fork()) {
      case 0:
	// child code: recieve data and send them back
	while( recv(newsockfd, &c, 1, 0) > 0 ) {
	  cout << c;
	  c = toupper(c);
	  // send it back!
	  send(newsockfd, &c, 1, 0);
	}
	break;
      default:
	// parent code
	break;
    }
  }
  
  return 0;
}

Kod kompiluje się, ale raczej nie działa albo źle obsługuję telnet. Chcąc podłączyć się wykonuje następujące polecenie:

$ telnet 127.0.0.1 1000
Trying 127.0.0.1...
telnet: connect to address 127.0.0.1: Connection refused

Gdy wykonam analogiczne połączenie na serwer SMTP to odzywa się sendmail (tyle, że podaje port 25).

Usługa cały czas działa tzn. w oknie obok proces serwera jest aktywny.

Co to może być?

Pozdrawiam,

0

Napisałem klienta:

#include <iostream>
#include <cstdlib>
#include <cctype>
#include <cstdio>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h> // struct sockaddr_in
#include <arpa/inet.h>
#include <unistd.h>

using namespace std;

/*
 *  Simple echo server to test exceptions in C++.
 */

#define PORT 1000

int main()
{
  int sockfd;
  sockaddr_in server = {AF_INET, PORT};
  pid_t pid;
  
  server.sin_addr.s_addr = inet_addr("127.0.0.1");
  
  
  if( (sockfd = socket(AF_INET, SOCK_STREAM, 0)) == -1 ) {
    cerr << "Socket call failed" << endl;
    exit(1);
  }
  
  // connect to server
  if( connect(sockfd, (sockaddr*) &server, sizeof(sockaddr_in)) == -1 ) {
    cerr << "connect call failed" << endl;
    exit(1);
  }
  
  // send and recieve data
  char c, rc;
  while(1) {
    c = getchar();
    send(sockfd, &c, 1, 0);
    recv(sockfd, &rc, 1, 0);
    cout << rc << endl;
  }
  
  return 0;
}

Jego łączenie z serwerem działa bez zarzutów - pytanie: dlaczego sam telnet nie radzi sobie z tym?

1 użytkowników online, w tym zalogowanych: 0, gości: 1