
November 9th, 2008, 09:35 PM
|
|
Registered User
|
|
Join Date: Nov 2008
Posts: 2
Time spent in forums: 1 h 5 m 38 sec
Reputation Power: 0
|
|
|
Ok, why won't this telnet client work?
Hello, I'm attempting to modify this example in order to create a program that can both send an receive data to and from a telnet server. What I'd like to do is have a framework that I can use any time I need to create a program that will communicate by telnet. I tried to make it so that in order to send something, all I need to do is add it to the 'output' string.
Anyways, it compiles fine, but when I try to connect it to a server that I know works, nothing happens. The couts don't even show up. I don't know enough about this kind of program to diagnose it myself, so I'd really appreciate it if I could get some help.
Code:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
#include <netdb.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <sys/socket.h>
#include <string>
#include <arpa/inet.h>
#define PORT "3000" // the port client will be connecting to
#define MAXDATASIZE 100 // max number of bytes we can get at once
#include <iostream>
std::string output,input;
void inputhandle (std::string input) {
std::cout <<"c"; //for diagnostic purposes
std::cout << input;
std::cin >> output;
return;
}
// get sockaddr, IPv4 or IPv6:
void *get_in_addr(struct sockaddr *sa)
{
if (sa->sa_family == AF_INET) {
return &(((struct sockaddr_in*)sa)->sin_addr);
}
return &(((struct sockaddr_in6*)sa)->sin6_addr);
}
int main(int argc, char *argv[])
{
int sockfd, numbytes;
char buf[MAXDATASIZE];
struct addrinfo hints, *servinfo, *p;
int rv;
char s[INET6_ADDRSTRLEN];
std::string output,input;
if (argc != 2) {
fprintf(stderr,"usage: client hostname\n");
exit(1);
}
memset(&hints, 0, sizeof hints);
hints.ai_family = AF_UNSPEC;
hints.ai_socktype = SOCK_STREAM;
if ((rv = getaddrinfo(argv[1], PORT, &hints, &servinfo)) != 0) {
fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(rv));
return 1;
}
// loop through all the results and connect to the first we can
for(p = servinfo; p != NULL; p = p->ai_next) {
if ((sockfd = socket(p->ai_family, p->ai_socktype,
p->ai_protocol)) == -1) {
perror("client: socket");
continue;
}
if (connect(sockfd, p->ai_addr, p->ai_addrlen) == -1) {
close(sockfd);
perror("client: connect");
continue;
}
break;
}
if (p == NULL) {
fprintf(stderr, "client: failed to connect\n");
return 2;
}
inet_ntop(p->ai_family, get_in_addr((struct sockaddr *)p->ai_addr),
s, sizeof s);
printf("client: connecting to %s\n", s);
freeaddrinfo(servinfo); // all done with this structure
while (1) {
//receive part
if ((numbytes = recv(sockfd, buf, MAXDATASIZE-1, 0)) == -1) {
perror("recv");
exit(1);
}
buf[numbytes] = '\0';
input = buf;
inputhandle(input);
//send part
send(sockfd, output.c_str(), output.length() + 1, 0);
input = "";
output = "";
}
close(sockfd);
return 0;
}
|