5
5
#include "interface.h"
6
6
#include <netinet/in.h>
7
7
#include <stdlib.h>
8
+ #include <netdb.h>
9
+ #include <arpa/inet.h>
8
10
9
11
int connect_to (const char * host , const unsigned short port );
10
12
struct Reply process_command (const int sockfd , char * command );
11
13
void enter_chatmode (const char * host , const int port );
14
+ int hostname_to_ip (char * hostname , char * ip );
12
15
int REPLY_SIZE = sizeof (struct Reply );
13
16
14
17
int main (int argc , char * * argv ){
15
18
//If not specified, use defaults.
16
19
char * host_addr = argc > 1 ? argv [1 ] : "chat-room-438.cf" ;
20
+ char * ip_addr [16 ];
21
+ hostname_to_ip (host_addr , ip_addr );
22
+
17
23
unsigned short port = argc > 2 ? atoi (argv [2 ]) : 59254 ;
18
24
// printf("Host = %s, Port = %d\n", host_addr, port);
19
25
20
- /* if(argc != 3){
26
+ /* if(argc != 3){
21
27
fprintf(stderr, "Usage: Enter host address and port number\n");
22
28
fprintf(stderr, "Example: ./a.out chat-room-438.cf 59254\n");
23
29
return EXIT_FAILURE;
24
- }*/
30
+ }*/
25
31
26
32
// Ping the Chatroom Manager to make sure we can send commands
27
- int sockfd = connect_to (host_addr , port );
33
+ int sockfd = connect_to (ip_addr , port );
28
34
if (sockfd < 0 || write (sockfd , "PING" , 4 ) < 0 ){
29
35
exit (EXIT_FAILURE );
30
36
}
@@ -40,15 +46,15 @@ int main(int argc, char** argv){
40
46
if (startswith (command , "EXIT" )) break ;
41
47
42
48
// Connect to the Chatroom Manager
43
- if ((sockfd = connect_to (host_addr , port )) < 0 ) exit (EXIT_FAILURE );
49
+ if ((sockfd = connect_to (ip_addr , port )) < 0 ) exit (EXIT_FAILURE );
44
50
45
51
// Send command to the Chatroom Manager
46
52
struct Reply reply = process_command (sockfd , command );
47
53
display_reply (command , reply );
48
54
49
55
// If a successful JOIN, put this client in chatmode
50
56
if (reply .status == SUCCESS && startswith (command , "JOIN" )){
51
- enter_chatmode (/*reply.host*/ host_addr , reply .port );
57
+ enter_chatmode (/*reply.host*/ ip_addr , reply .port );
52
58
}
53
59
}
54
60
}
@@ -163,4 +169,20 @@ void enter_chatmode(const char* host, const int port){
163
169
164
170
close (chat_server );
165
171
printf ("Exiting ChatMode\n" );
166
- }
172
+ }
173
+
174
+ int hostname_to_ip (char * hostname , char * ip ){
175
+ struct hostent * he ;
176
+ struct in_addr * * addr_list ;
177
+ int i ;
178
+ if ((he = gethostbyname (hostname ))){
179
+ addr_list = (struct in_addr * * ) he -> h_addr_list ;
180
+ for (i = 0 ; addr_list [i ]; ++ i ){
181
+ // Return the file one
182
+ strcpy (ip , inet_ntoa (* addr_list [i ]));
183
+ return EXIT_SUCCESS ;
184
+ }
185
+ }
186
+ herror ("gethostbyname" );
187
+ return EXIT_FAILURE ;
188
+ }
0 commit comments