Reputation: 43
I'm designing a pair of c programs that uses basic stream sockets to communicate between two programs, similar to a server-client interaction. Most of the programs seem to work fine, but the client end of the system keeps reporting an error that I can't quite work out.
The client program, once compiled, is executed using a command line argument, which as I understand is supposed to be the name of the server program. However, every time I run the following line
./client server
I get an error that only gets reported in the event that argv[1] is null. Here's the code from string_client.c:
if ((he=gethostbyname(argv[1])) == NULL) { // get the host info
perror("gethostbyname");
printf("%s", argv[1]);
exit(1);
}
server is just the executable file from string_server.c, which is supposed to wait for an incoming request from the client and receive input from the client program(and works as far as that, as far as I can tell). I'm not sure about the gethostbyname method, but as that code was provided, I haven't questioned it yet.
Also, whenever I try printing out argv[1], it comes out as "la"... not sure what's happening there. What's going on with the command line? am I just using the wrong argument?
Upvotes: 0
Views: 291
Reputation: 2762
Here you go:
#include <stdio.h>
#include <netdb.h>
extern int h_errno;
int main(int argc, char **argv)
{
struct hostent *he;
if(argc < 2)
{
printf("usage: %s hostname\n", argv[0]);
return 255;
}
if ((he=gethostbyname(argv[1])) == NULL) { // get the host info
perror("gethostbyname");
printf("%s", argv[1]);
return 1;
}
printf("%s resolved to %u.%u.%u.%u\n", argv[1],
(unsigned char)(he->h_addr_list[0][0]),
(unsigned char)(he->h_addr_list[0][1]),
(unsigned char)(he->h_addr_list[0][2]),
(unsigned char)(he->h_addr_list[0][3]));
return 0;
}
It works now:
$ gcc -Wall -o gethost gethost.c
$ ./gethost
usage: ./gethost hostname
$ ./gethost google.com
google.com resolved to 173.194.40.196
$ ./gethost localhost
localhost resolved to 127.0.0.1
Upvotes: 3