@@ -1072,7 +1072,7 @@ bufferedStream::~bufferedStream() {
10721072#include < netinet/in.h>
10731073#include < arpa/inet.h>
10741074#elif defined(_WINDOWS)
1075- #include < winsock2 .h>
1075+ #include < Ws2tcpip .h>
10761076#endif
10771077
10781078// Network access
@@ -1113,25 +1113,31 @@ void networkStream::close() {
11131113 }
11141114}
11151115
1116- bool networkStream::connect (const char *ip, short port) {
1116+ // host could be IP address, or a host name
1117+ bool networkStream::connect (const char *host, short port) {
11171118
1118- struct sockaddr_in server;
1119- server. sin_family = AF_INET ;
1120- server. sin_port = htons (port );
1119+ char s_port[ 6 ]; // 5 digits max plus terminator
1120+ int ret = os::snprintf (s_port, sizeof (s_port), " %hu " , ( unsigned short ) port) ;
1121+ assert (ret > 0 , " snprintf failed: %d " , ret );
11211122
1122- server.sin_addr .s_addr = inet_addr (ip);
1123- if (server.sin_addr .s_addr == (uint32_t )-1 ) {
1124- struct hostent * host = os::get_host_by_name ((char *)ip);
1125- if (host != NULL ) {
1126- memcpy (&server.sin_addr , host->h_addr_list [0 ], host->h_length );
1127- } else {
1128- return false ;
1129- }
1130- }
1123+ struct addrinfo * addr_info = NULL ;
1124+ struct addrinfo hints;
11311125
1126+ memset (&hints, 0 , sizeof (hints));
1127+ hints.ai_family = AF_INET; // Allow IPv4 only
1128+ hints.ai_socktype = SOCK_STREAM; // TCP only
1129+
1130+ // getaddrinfo can resolve both an IP address and a host name
1131+ ret = getaddrinfo (host, s_port, &hints, &addr_info);
1132+ if (ret != 0 ) {
1133+ warning (" networkStream::connect getaddrinfo for host %s and port %s failed: %s" ,
1134+ host, s_port, gai_strerror (ret));
1135+ return false ;
1136+ }
11321137
1133- int result = os::connect (_socket, (struct sockaddr *)&server, sizeof (struct sockaddr_in ));
1134- return (result >= 0 );
1138+ ret = os::connect (_socket, addr_info->ai_addr , (socklen_t )addr_info->ai_addrlen );
1139+ freeaddrinfo (addr_info);
1140+ return (ret >= 0 );
11351141}
11361142
11371143#endif
0 commit comments