| 299 | |
| 300 | |
| 301 | Conn connect(std::string host, uint16_t port) { |
| 302 | Socket sock; |
| 303 | |
| 304 | #ifdef _WIN32 |
| 305 | // Initialize WinSock2 |
| 306 | if (!winsock_init) { |
| 307 | WSADATA wsa; |
| 308 | if (WSAStartup(MAKEWORD(2,2),&wsa)) { |
| 309 | throw std::runtime_error("Could not initialize WinSock2"); |
| 310 | return NULL; |
| 311 | } |
| 312 | winsock_init = true; |
| 313 | } |
| 314 | assert(winsock_init); |
| 315 | #else |
| 316 | signal(SIGPIPE, SIG_IGN); |
| 317 | #endif |
| 318 | |
| 319 | // Create a socket |
| 320 | sock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); |
| 321 | if (sock < 0) { |
| 322 | throw std::runtime_error("Could not create socket"); |
| 323 | return NULL; |
| 324 | } |
| 325 | |
| 326 | // Get address from hostname/ip |
| 327 | hostent* remoteHost = gethostbyname(host.c_str()); |
| 328 | if (remoteHost == NULL || remoteHost->h_addr_list[0] == NULL) { |
| 329 | throw std::runtime_error("Could get address from host"); |
| 330 | return NULL; |
| 331 | } |
| 332 | uint32_t* naddr = (uint32_t*)remoteHost->h_addr_list[0]; |
| 333 | |
| 334 | // Create host address |
| 335 | struct sockaddr_in addr; |
| 336 | addr.sin_addr.s_addr = *naddr; |
| 337 | addr.sin_family = AF_INET; |
| 338 | addr.sin_port = htons(port); |
| 339 | |
| 340 | // Connect to host |
| 341 | if (::connect(sock, (struct sockaddr*)&addr, sizeof(addr)) < 0) { |
| 342 | throw std::runtime_error("Could not connect to host"); |
| 343 | return NULL; |
| 344 | } |
| 345 | |
| 346 | return Conn(new ConnClass(sock)); |
| 347 | } |
| 348 | |
| 349 | Listener listen(std::string host, uint16_t port) { |
| 350 | Socket listenSock; |