| 125 | // ----------------- |
| 126 | |
| 127 | int |
| 128 | hostname_to_ip ( |
| 129 | const std::string& hostname, |
| 130 | std::string& ip, |
| 131 | int n |
| 132 | ) |
| 133 | { |
| 134 | // ensure that WSAStartup has been called and WSACleanup will eventually |
| 135 | // be called when program ends |
| 136 | sockets_startup(); |
| 137 | |
| 138 | try |
| 139 | { |
| 140 | // lock this mutex since gethostbyname isn't really thread safe |
| 141 | auto_mutex M(sockets_kernel_1_mutex::startup_lock); |
| 142 | |
| 143 | // if no hostname was given then return error |
| 144 | if ( hostname.empty()) |
| 145 | return OTHER_ERROR; |
| 146 | |
| 147 | hostent* address; |
| 148 | address = gethostbyname(hostname.c_str()); |
| 149 | |
| 150 | if (address == 0) |
| 151 | { |
| 152 | return OTHER_ERROR; |
| 153 | } |
| 154 | |
| 155 | // find the nth address |
| 156 | in_addr* addr = reinterpret_cast<in_addr*>(address->h_addr_list[0]); |
| 157 | for (int i = 1; i <= n; ++i) |
| 158 | { |
| 159 | addr = reinterpret_cast<in_addr*>(address->h_addr_list[i]); |
| 160 | |
| 161 | // if there is no nth address then return error |
| 162 | if (addr == 0) |
| 163 | return OTHER_ERROR; |
| 164 | } |
| 165 | |
| 166 | char* resolved_ip = inet_ntoa(*addr); |
| 167 | |
| 168 | // check if inet_ntoa returned an error |
| 169 | if (resolved_ip == NULL) |
| 170 | { |
| 171 | return OTHER_ERROR; |
| 172 | } |
| 173 | |
| 174 | ip.assign(resolved_ip); |
| 175 | |
| 176 | } |
| 177 | catch(...) |
| 178 | { |
| 179 | return OTHER_ERROR; |
| 180 | } |
| 181 | |
| 182 | return 0; |
| 183 | } |
| 184 |
nothing calls this directly
no test coverage detected