| 227 | } |
| 228 | |
| 229 | void NetworkServer::StartServer() |
| 230 | { |
| 231 | int err; |
| 232 | struct addrinfo hints, *res, *result; |
| 233 | //Start a TCP server and launch threads |
| 234 | char port_str[6]; |
| 235 | snprintf(port_str, 6, "%d", port_num); |
| 236 | |
| 237 | socket_count = 0; |
| 238 | |
| 239 | /*-------------------------------------------------*\ |
| 240 | | Windows requires WSAStartup before using sockets | |
| 241 | \*-------------------------------------------------*/ |
| 242 | #ifdef WIN32 |
| 243 | if(WSAStartup(MAKEWORD(2, 2), &wsa) != NO_ERROR) |
| 244 | { |
| 245 | WSACleanup(); |
| 246 | return; |
| 247 | } |
| 248 | #endif |
| 249 | |
| 250 | memset(&hints, 0, sizeof(hints)); |
| 251 | hints.ai_family = AF_UNSPEC; |
| 252 | hints.ai_socktype = SOCK_STREAM; |
| 253 | hints.ai_flags = AI_PASSIVE; |
| 254 | err = getaddrinfo(host.c_str(), port_str, &hints, &result); |
| 255 | |
| 256 | if(err) |
| 257 | { |
| 258 | printf("Error: Unable to get address.\n"); |
| 259 | WSACleanup(); |
| 260 | return; |
| 261 | } |
| 262 | |
| 263 | /*-------------------------------------------------*\ |
| 264 | | Create a server socket for each address returned. | |
| 265 | \*-------------------------------------------------*/ |
| 266 | for(res = result; res && socket_count < MAXSOCK; res = res->ai_next) |
| 267 | { |
| 268 | server_sock[socket_count] = socket(res->ai_family, res->ai_socktype, res->ai_protocol); |
| 269 | |
| 270 | if(server_sock[socket_count] == INVALID_SOCKET) |
| 271 | { |
| 272 | printf("Error: network socket could not be created\n"); |
| 273 | WSACleanup(); |
| 274 | return; |
| 275 | } |
| 276 | |
| 277 | /*-------------------------------------------------*\ |
| 278 | | Bind the server socket | |
| 279 | \*-------------------------------------------------*/ |
| 280 | if(bind(server_sock[socket_count], res->ai_addr, res->ai_addrlen) == SOCKET_ERROR) |
| 281 | { |
| 282 | if(errno == EADDRINUSE) |
| 283 | { |
| 284 | printf("Error: Could not bind network socket \nIs port %hu already being used?\n", GetPort()); |
| 285 | } |
| 286 | else if(errno == EACCES) |
no test coverage detected