views:

37

answers:

1

I am writing c++ code for a telnet client. I am having problems getting the host address from the user input.

struct in_addr peers;

cin>>peers;

peerserver = gethostbyaddr((const char*)peers,4,AF_INET);

if (peerserver == NULL)
    exit(0);

I am new to c++, can anyone suggest a better way of getting the host addr with user input. Thanks in advance.

+1  A: 

What you're looking for is gethostbyname, not gethostbyaddr. gethostbyaddr assumes that you've already got the IP address.

char peers[256];
cin >> peers;
struct hostent *ent = gethostbyname(peers);
printf("%04x\n", *(int *)(ent->h_addr));
Eric Warmenhoven
Better yet, use an `std::string` and getaddrinfo (http://linux.die.net/man/3/getaddrinfo)
larsmans
... and not forgetting that `getaddrinfo` (and now mostly obsolete `gethostby*` functions) may return several addresses/entries. Relation `name <-> address` is many to many.
Dummy00001