Skip to content

Commit eb4cf08

Browse files
committed
get hostname rather than ip address from command line
1 parent e11c0ec commit eb4cf08

File tree

1 file changed

+8
-7
lines changed

1 file changed

+8
-7
lines changed

client.c

+8-7
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@
1111
#include <netinet/in.h>
1212
#include <arpa/inet.h>
1313
#include <sys/select.h>
14+
#include <netdb.h>
1415

1516

1617
#define DEFAULT_SERVER_PORT 5432
@@ -24,15 +25,16 @@ int main(int argc, char *argv[])
2425
int addrlen = sizeof(struct sockaddr_in);
2526
char message[MAX_MSG_SIZE + 1];
2627

27-
char hostip[20];
28+
char hostname[MAX_MSG_SIZE];
29+
struct hostent *hostinfo;
2830

2931
//parse command line arguments
3032
if(argc == 2){
31-
strcpy(hostip, argv[1]);
33+
strcpy(hostname, argv[1]);
3234
} else if(argc == 4){
3335
if(!strcmp("-p", argv[1])){
3436
sscanf(argv[2], "%d", &port);
35-
strcpy(hostip, argv[3]);
37+
strcpy(hostname, argv[3]);
3638
} else{
3739
printf("Usage: %s [-p PORT] HOST-IP-ADDRESS\n", argv[0]);
3840
exit(0);
@@ -46,10 +48,9 @@ int main(int argc, char *argv[])
4648
client_sockfd = socket(AF_INET, SOCK_STREAM, 0);
4749
server_addr.sin_family = AF_INET;
4850
server_addr.sin_port = htons(port);
49-
if(inet_aton(hostip, &server_addr.sin_addr) < 0){
50-
perror("inet_aton");
51-
exit(1);
52-
}
51+
52+
hostinfo = gethostbyname(hostname);
53+
server_addr.sin_addr = *(struct in_addr *) *hostinfo -> h_addr_list;
5354

5455
//connect to server
5556
if(connect(client_sockfd, (struct sockaddr *) &server_addr, addrlen) < 0){

0 commit comments

Comments
 (0)