AJ_Status AJ_Net_Connect(AJ_BusAttachment* bus, const AJ_Service* service) { AJ_Status status = AJ_ERR_CONNECT; /* Initialize Winsock, if not done already */ WinsockCheck(); #ifdef AJ_ARDP if (service->addrTypes & (AJ_ADDR_UDP4 | AJ_ADDR_UDP6)) { status = AJ_Net_ARDP_Connect(bus, service); if (status == AJ_OK) { return status; } } #endif #ifdef AJ_TCP if (service->addrTypes & (AJ_ADDR_TCP4 | AJ_ADDR_TCP6)) { status = AJ_TCP_Connect(bus, service); } #endif return status; }
AJ_Status AJ_Net_Connect(AJ_BusAttachment* bus, const AJ_Service* service) { DWORD ret; SOCKADDR_STORAGE addrBuf; socklen_t addrSize; SOCKET sock; /* Initialize Winsock, if not done already */ WinsockCheck(); #ifdef AJ_ARDP if (service->addrTypes & (AJ_ADDR_UDP4 | AJ_ADDR_UDP6)) { return AJ_Net_ARDP_Connect(bus, service); } #endif AJ_InfoPrintf(("AJ_Net_Connect(bus=0x%p, addrType=%d.)\n", bus, service->addrTypes)); memset(&addrBuf, 0, sizeof(addrBuf)); if (service->addrTypes & AJ_ADDR_TCP4) { struct sockaddr_in* sa = (struct sockaddr_in*)&addrBuf; sock = WSASocket(AF_INET, SOCK_STREAM, IPPROTO_TCP, NULL, 0, WSA_FLAG_OVERLAPPED); if (sock == INVALID_SOCKET) { AJ_ErrPrintf(("AJ_Net_Connect(): invalid socket. status=AJ_ERR_CONNECT\n")); return AJ_ERR_CONNECT; } sa->sin_family = AF_INET; sa->sin_port = htons(service->ipv4port); sa->sin_addr.s_addr = service->ipv4; addrSize = sizeof(*sa); AJ_InfoPrintf(("AJ_Net_Connect(): Connect to \"%s:%u\"\n", inet_ntoa(sa->sin_addr), service->ipv4port));; } else if (service->addrTypes & AJ_ADDR_TCP6) { struct sockaddr_in6* sa = (struct sockaddr_in6*)&addrBuf; sock = WSASocket(AF_INET6, SOCK_STREAM, IPPROTO_TCP, NULL, 0, WSA_FLAG_OVERLAPPED); if (sock == INVALID_SOCKET) { AJ_ErrPrintf(("AJ_Net_Connect(): invalid socket. status=AJ_ERR_CONNECT\n")); return AJ_ERR_CONNECT; } sa->sin6_family = AF_INET6; sa->sin6_port = htons(service->ipv6port); memcpy(sa->sin6_addr.s6_addr, service->ipv6, sizeof(sa->sin6_addr.s6_addr)); addrSize = sizeof(*sa); } else { AJ_ErrPrintf(("AJ_Net_Connect: only TCPv6 and TCPv4 are supported\n")); return AJ_ERR_CONNECT; } ret = connect(sock, (struct sockaddr*)&addrBuf, addrSize); if (ret == SOCKET_ERROR) { AJ_ErrPrintf(("AJ_Net_Connect(): connect() failed. WSAGetLastError()=0x%x, status=AJ_ERR_CONNECT\n", WSAGetLastError())); closesocket(sock); return AJ_ERR_CONNECT; } else { AJ_IOBufInit(&bus->sock.rx, rxData, sizeof(rxData), AJ_IO_BUF_RX, &netContext); bus->sock.rx.recv = AJ_Net_Recv; AJ_IOBufInit(&bus->sock.tx, txData, sizeof(txData), AJ_IO_BUF_TX, &netContext); bus->sock.tx.send = AJ_Net_Send; netContext.tcpSock = sock; AJ_InfoPrintf(("AJ_Net_Connect(): status=AJ_OK\n")); sendEvent = CreateEvent(NULL, TRUE, FALSE, NULL); recvEvent = CreateEvent(NULL, TRUE, FALSE, NULL); interruptEvent = CreateEvent(NULL, TRUE, FALSE, NULL); wsaOverlapped.hEvent = INVALID_HANDLE_VALUE; return AJ_OK; } }