@@ -1089,7 +1089,7 @@ bufferedStream::~bufferedStream() {
10891089#include < netdb.h>
10901090#include < arpa/inet.h>
10911091#elif defined(_WINDOWS)
1092- #include < winsock2 .h>
1092+ #include < Ws2tcpip .h>
10931093#endif
10941094
10951095// Network access
@@ -1130,25 +1130,31 @@ void networkStream::close() {
11301130 }
11311131}
11321132
1133- bool networkStream::connect (const char *ip, short port) {
1133+ // host could be IP address, or a host name
1134+ bool networkStream::connect (const char *host, short port) {
11341135
1135- struct sockaddr_in server;
1136- server. sin_family = AF_INET ;
1137- server. sin_port = htons (port );
1136+ char s_port[ 6 ]; // 5 digits max plus terminator
1137+ int ret = os::snprintf (s_port, sizeof (s_port), " %hu " , ( unsigned short ) port) ;
1138+ assert (ret > 0 , " snprintf failed: %d " , ret );
11381139
1139- server.sin_addr .s_addr = inet_addr (ip);
1140- if (server.sin_addr .s_addr == (uint32_t )-1 ) {
1141- struct hostent * host = os::get_host_by_name ((char *)ip);
1142- if (host != nullptr ) {
1143- memcpy (&server.sin_addr , host->h_addr_list [0 ], host->h_length );
1144- } else {
1145- return false ;
1146- }
1147- }
1140+ struct addrinfo * addr_info = nullptr ;
1141+ struct addrinfo hints;
11481142
1143+ memset (&hints, 0 , sizeof (hints));
1144+ hints.ai_family = AF_INET; // Allow IPv4 only
1145+ hints.ai_socktype = SOCK_STREAM; // TCP only
1146+
1147+ // getaddrinfo can resolve both an IP address and a host name
1148+ ret = getaddrinfo (host, s_port, &hints, &addr_info);
1149+ if (ret != 0 ) {
1150+ warning (" networkStream::connect getaddrinfo for host %s and port %s failed: %s" ,
1151+ host, s_port, gai_strerror (ret));
1152+ return false ;
1153+ }
11491154
1150- int result = os::connect (_socket, (struct sockaddr *)&server, sizeof (struct sockaddr_in ));
1151- return (result >= 0 );
1155+ ret = os::connect (_socket, addr_info->ai_addr , (socklen_t )addr_info->ai_addrlen );
1156+ freeaddrinfo (addr_info);
1157+ return (ret >= 0 );
11521158}
11531159
11541160#endif
0 commit comments