TCPSocket::TCPSocket(SocketHandle boundHandle, bool isListenSocket) { TheSocket = boundHandle; IsListenSocket = isListenSocket; IsConnecting = false; SetSocketOptions(TheSocket); // The actual socket is always non-blocking _Ioctlsocket(TheSocket, 1); }
TInt32 CListener::Init(HANDLE completionPort,TUInt32 myIp,TUInt16 listeningPort,TUInt16 maxAcceptNr,IfListenerCallBack *pListenerCallBack,ItemClassPool<CConnection> *pConnectionPool,IfParserFactory *pParserFactory,IfCryptorFactory *pCryptorFactory) { m_compeltionPort = completionPort; m_myIp = myIp; m_listeningPort = listeningPort; m_pNext = NULL; m_listeningSocket = WSASocket(AF_INET, SOCK_STREAM, IPPROTO_IP, NULL, 0, WSA_FLAG_OVERLAPPED); if (SOCKET_ERROR == m_listeningSocket) { int errCode = GetLastError(); return -errCode; } TInt32 ret = SetSocketOptions(m_listeningSocket); if (SUCCESS > ret) { closesocket(m_listeningSocket); return ret; } SOCKADDR_IN myAdd; SecureZeroMemory(&myAdd,sizeof(SOCKADDR_IN)); myAdd.sin_port = htons(listeningPort); // Fill in the rest of the address structure myAdd.sin_family = AF_INET; myAdd.sin_addr.s_addr = myIp; // bind our name to the socket ret = bind(m_listeningSocket, (LPSOCKADDR)&myAdd, sizeof(struct sockaddr)); if(ret == SOCKET_ERROR) { closesocket(m_listeningSocket); m_listeningSocket = 0; return FAIL; } ret = listen(m_listeningSocket, maxAcceptNr); if ( ret == SOCKET_ERROR ) { closesocket(m_listeningSocket); return False; } m_maxAcceptNr = maxAcceptNr; m_pListenerCallBack = pListenerCallBack; m_pConnectionPool = pConnectionPool; m_pParserFactory = pParserFactory; m_pCryptorFactory = pCryptorFactory; return SUCCESS; }
static SocketHandle BindShared(int ai_family, int ai_socktype, BerkleyBindParameters *pBindParameters) { SocketHandle sock; struct addrinfo hints; memset(&hints, 0, sizeof (addrinfo)); // make sure the struct is empty hints.ai_family = ai_family; hints.ai_socktype = ai_socktype; hints.ai_flags = AI_PASSIVE; // fill in my IP for me struct addrinfo *servinfo=0, *aip; // will point to the results char portStr[32]; OVR_itoa(pBindParameters->Port, portStr, sizeof(portStr), 10); int errcode = 0; if (!pBindParameters->Address.IsEmpty()) errcode = getaddrinfo(pBindParameters->Address.ToCStr(), portStr, &hints, &servinfo); else errcode = getaddrinfo(0, portStr, &hints, &servinfo); if (0 != errcode) { OVR::LogError("getaddrinfo error: %s", gai_strerror(errcode)); } for (aip = servinfo; aip != NULL; aip = aip->ai_next) { // Open socket. The address type depends on what // getaddrinfo() gave us. sock = socket(aip->ai_family, aip->ai_socktype, aip->ai_protocol); if (sock != 0) { SetSocketOptions(sock); int ret = bind( sock, aip->ai_addr, (int) aip->ai_addrlen ); if (ret>=0) { // The actual socket is always non-blocking // I control blocking or not using WSAEventSelect _Ioctlsocket(sock, 1); freeaddrinfo(servinfo); return sock; } else { close(sock); } } } if (servinfo) { freeaddrinfo(servinfo); } return INVALID_SOCKET; }
bool Socket::SetNoDelay (bool _bNoDelay) { if (true == b_UnixDomain) return false; int iNoDelayFlag = 1; if (false == _bNoDelay) iNoDelayFlag = 0; return SetSocketOptions (IPPROTO_TCP, TCP_NODELAY, (char *)&iNoDelayFlag, sizeof(iNoDelayFlag)); }
void Client::Connect( ) { int rc; SockAddr_remoteAddr( mSettings ); assert( mSettings->inHostname != NULL ); // create an internet socket int type = ( isUDP( mSettings ) ? SOCK_DGRAM : SOCK_STREAM); int domain = (SockAddr_isIPv6( &mSettings->peer ) ? #ifdef HAVE_IPV6 AF_INET6 #else AF_INET #endif : AF_INET); mSettings->mSock = socket( domain, type, 0 ); WARN_errno( mSettings->mSock == INVALID_SOCKET, "socket" ); SetSocketOptions( mSettings ); SockAddr_localAddr( mSettings ); if ( mSettings->mLocalhost != NULL ) { // bind socket to local address char temp[100] = "cbind:"; SockAddr_getHostAddress(&mSettings->local, &temp[6], 94); rc = bind( mSettings->mSock, (sockaddr*) &mSettings->local, SockAddr_get_sizeof_sockaddr( &mSettings->local ) ); WARN_errno( rc == SOCKET_ERROR, temp ); } // connect socket rc = connect( mSettings->mSock, (sockaddr*) &mSettings->peer, SockAddr_get_sizeof_sockaddr( &mSettings->peer )); FAIL_errno( rc == SOCKET_ERROR, "connect", mSettings ); getsockname( mSettings->mSock, (sockaddr*) &mSettings->local, &mSettings->size_local ); getpeername( mSettings->mSock, (sockaddr*) &mSettings->peer, &mSettings->size_peer ); } // end Connect
RNS2BindResult RNS2_Berkley::BindSharedIPV4And6( RNS2_BerkleyBindParameters *bindParameters, const char *file, unsigned int line ) { (void) file; (void) line; (void) bindParameters; #if RAKNET_SUPPORT_IPV6==1 int ret=0; struct addrinfo hints; struct addrinfo *servinfo=0, *aip; // will point to the results PrepareAddrInfoHints2(&hints); hints.ai_family=bindParameters->addressFamily; char portStr[32]; Itoa(bindParameters->port,portStr,10); // On Ubuntu, "" returns "No address associated with hostname" while 0 works. if (bindParameters->hostAddress && (_stricmp(bindParameters->hostAddress,"UNASSIGNED_SYSTEM_ADDRESS")==0 || bindParameters->hostAddress[0]==0)) { getaddrinfo(0, portStr, &hints, &servinfo); } else { getaddrinfo(bindParameters->hostAddress, portStr, &hints, &servinfo); } // Try all returned addresses until one works for (aip = servinfo; aip != NULL; aip = aip->ai_next) { // Open socket. The address type depends on what // getaddrinfo() gave us. rns2Socket = socket__(aip->ai_family, aip->ai_socktype, aip->ai_protocol); if (rns2Socket == -1) return BR_FAILED_TO_BIND_SOCKET; ret = bind__(rns2Socket, aip->ai_addr, (int) aip->ai_addrlen ); if (ret>=0) { // Is this valid? memcpy(&boundAddress.address.addr6, aip->ai_addr, sizeof(boundAddress.address.addr6)); freeaddrinfo(servinfo); // free the linked-list SetSocketOptions(); SetNonBlockingSocket(bindParameters->nonBlockingSocket); SetBroadcastSocket(bindParameters->setBroadcast); GetSystemAddressIPV4And6( rns2Socket, &boundAddress ); return BR_SUCCESS; } else { closesocket__(rns2Socket); } } return BR_FAILED_TO_BIND_SOCKET; #else return BR_REQUIRES_RAKNET_SUPPORT_IPV6_DEFINE; #endif }
RNS2BindResult RNS2_Berkley::BindSharedIPV4( RNS2_BerkleyBindParameters *bindParameters, const char *file, unsigned int line ) { (void) file; (void) line; int ret; memset(&boundAddress.address.addr4,0,sizeof(sockaddr_in)); boundAddress.address.addr4.sin_port = htons( bindParameters->port ); rns2Socket = (int) socket__( bindParameters->addressFamily, bindParameters->type, bindParameters->protocol ); if (rns2Socket == -1) return BR_FAILED_TO_BIND_SOCKET; SetSocketOptions(); SetNonBlockingSocket(bindParameters->nonBlockingSocket); SetBroadcastSocket(bindParameters->setBroadcast); // Fill in the rest of the address structure boundAddress.address.addr4.sin_family = AF_INET; if (bindParameters->hostAddress && bindParameters->hostAddress[0]) { boundAddress.address.addr4.sin_addr.s_addr = inet_addr__( bindParameters->hostAddress ); } else { // RAKNET_DEBUG_PRINTF("Binding any on port %i\n", port); boundAddress.address.addr4.sin_addr.s_addr = INADDR_ANY; } // bind our name to the socket ret = bind__( rns2Socket, ( struct sockaddr * ) &boundAddress.address.addr4, sizeof( boundAddress.address.addr4 ) ); if ( ret <= -1 ) { #if defined(_WIN32) closesocket__(rns2Socket); return BR_FAILED_TO_BIND_SOCKET; #elif (defined(__GNUC__) || defined(__GCCXML__) ) && !defined(_WIN32) closesocket__(rns2Socket); switch (ret) { case EBADF: RAKNET_DEBUG_PRINTF("bind__(): sockfd is not a valid descriptor.\n"); break; case ENOTSOCK: RAKNET_DEBUG_PRINTF("bind__(): Argument is a descriptor for a file, not a socket.\n"); break; case EINVAL: RAKNET_DEBUG_PRINTF("bind__(): The addrlen is wrong, or the socket was not in the AF_UNIX family.\n"); break; case EROFS: RAKNET_DEBUG_PRINTF("bind__(): The socket inode would reside on a read-only file system.\n"); break; case EFAULT: RAKNET_DEBUG_PRINTF("bind__(): my_addr points outside the user's accessible address space.\n"); break; case ENAMETOOLONG: RAKNET_DEBUG_PRINTF("bind__(): my_addr is too long.\n"); break; case ENOENT: RAKNET_DEBUG_PRINTF("bind__(): The file does not exist.\n"); break; case ENOMEM: RAKNET_DEBUG_PRINTF("bind__(): Insufficient kernel memory was available.\n"); break; case ENOTDIR: RAKNET_DEBUG_PRINTF("bind__(): A component of the path prefix is not a directory.\n"); break; case EACCES: RAKNET_DEBUG_PRINTF("bind__(): Search permission is denied on a component of the path prefix.\n"); break; case ELOOP: RAKNET_DEBUG_PRINTF("bind__(): Too many symbolic links were encountered in resolving my_addr.\n"); break; default: RAKNET_DEBUG_PRINTF("Unknown bind__() error %i.\n", ret); break; } #endif return BR_FAILED_TO_BIND_SOCKET; } GetSystemAddressIPV4(rns2Socket, &boundAddress ); return BR_SUCCESS; }
/** * This function implements jdwpTransportEnv::StartListening */ static jdwpTransportError JNICALL TCPIPSocketTran_StartListening(jdwpTransportEnv* env, const char* address, char** actualAddress) { SOCKET envClientSocket = ((internalEnv*)env->functions->reserved1)->envClientSocket; if (envClientSocket != INVALID_SOCKET) { SetLastTranError(env, "there is already an open connection to the debugger", 0); return JDWPTRANSPORT_ERROR_ILLEGAL_STATE ; } SOCKET envServerSocket = ((internalEnv*)env->functions->reserved1)->envServerSocket; if (envServerSocket != INVALID_SOCKET) { SetLastTranError(env, "transport is currently in listen mode", 0); return JDWPTRANSPORT_ERROR_ILLEGAL_STATE ; } jdwpTransportError res; struct sockaddr_in serverSockAddr; res = DecodeAddress(env, address, &serverSockAddr, true); if (res != JDWPTRANSPORT_ERROR_NONE) { return res; } SOCKET serverSocket = socket(AF_INET, SOCK_STREAM, 0); if (serverSocket == INVALID_SOCKET) { SetLastTranError(env, "unable to create socket", GetLastErrorStatus()); return JDWPTRANSPORT_ERROR_IO_ERROR; } if (!SetSocketOptions(env, serverSocket)) { return JDWPTRANSPORT_ERROR_IO_ERROR; } int err; err = bind(serverSocket, (struct sockaddr *)&serverSockAddr, sizeof(serverSockAddr)); if (err == SOCKET_ERROR) { SetLastTranError(env, "binding to port failed", GetLastErrorStatus()); return JDWPTRANSPORT_ERROR_ILLEGAL_STATE ; } err = listen(serverSocket, SOMAXCONN); if (err == SOCKET_ERROR) { SetLastTranError(env, "listen start failed", GetLastErrorStatus()); return JDWPTRANSPORT_ERROR_ILLEGAL_STATE ; } if (!SetSocketBlockingMode(env, serverSocket, false)) { return JDWPTRANSPORT_ERROR_IO_ERROR; } ((internalEnv*)env->functions->reserved1)->envServerSocket = serverSocket; socklen_t len = sizeof(serverSockAddr); err = getsockname(serverSocket, (struct sockaddr *)&serverSockAddr, &len); if (err == SOCKET_ERROR) { SetLastTranError(env, "socket error", GetLastErrorStatus()); return JDWPTRANSPORT_ERROR_ILLEGAL_STATE ; } char* retAddress = 0; // RI always returns only port number in listening mode /* char portName[6]; sprintf(portName, "%d", ntohs(serverSockAddr.sin_port)); //instead of itoa() char hostName[NI_MAXHOST]; if (getnameinfo((struct sockaddr *)&serverSockAddr, len, hostName, sizeof(hostName), NULL, 0, 0)) { return JDWPTRANSPORT_ERROR_IO_ERROR; } if (strcmp(hostName, "0.0.0.0") == 0) { gethostname(hostName, sizeof(hostName)); } retAddress = (char*)(((internalEnv*)env->functions->reserved1) ->alloc)((jint)(strlen(hostName) + strlen(portName) + 2)); if (retAddress == 0) { SetLastTranError(env, "out of memory", 0); return JDWPTRANSPORT_ERROR_OUT_OF_MEMORY; } sprintf(retAddress, "%s:%s", hostName, portName); */ retAddress = (char*)(((internalEnv*)env->functions->reserved1)->alloc)(6 + 1); if (retAddress == 0) { SetLastTranError(env, "out of memory", 0); return JDWPTRANSPORT_ERROR_OUT_OF_MEMORY; } sprintf(retAddress, "%d", ntohs(serverSockAddr.sin_port)); *actualAddress = retAddress; return JDWPTRANSPORT_ERROR_NONE; } //TCPIPSocketTran_StartListening
/** * This function implements jdwpTransportEnv::Attach */ static jdwpTransportError JNICALL TCPIPSocketTran_Attach(jdwpTransportEnv* env, const char* address, jlong attachTimeout, jlong handshakeTimeout) { if ((address == 0) || (*address == 0)) { SetLastTranError(env, "address is missing", 0); return JDWPTRANSPORT_ERROR_ILLEGAL_ARGUMENT; } if (attachTimeout < 0) { SetLastTranError(env, "attachTimeout timeout is negative", 0); return JDWPTRANSPORT_ERROR_ILLEGAL_ARGUMENT; } if (handshakeTimeout < 0) { SetLastTranError(env, "handshakeTimeout timeout is negative", 0); return JDWPTRANSPORT_ERROR_ILLEGAL_ARGUMENT; } SOCKET envClientSocket = ((internalEnv*)env->functions->reserved1)->envClientSocket; if (envClientSocket != INVALID_SOCKET) { SetLastTranError(env, "there is already an open connection to the debugger", 0); return JDWPTRANSPORT_ERROR_ILLEGAL_STATE ; } SOCKET envServerSocket = ((internalEnv*)env->functions->reserved1)->envServerSocket; if (envServerSocket != INVALID_SOCKET) { SetLastTranError(env, "transport is currently in listen mode", 0); return JDWPTRANSPORT_ERROR_ILLEGAL_STATE ; } struct sockaddr_in serverSockAddr; jdwpTransportError res = DecodeAddress(env, address, &serverSockAddr, false); if (res != JDWPTRANSPORT_ERROR_NONE) { return res; } SOCKET clientSocket = socket(AF_INET, SOCK_STREAM, 0); if (clientSocket == INVALID_SOCKET) { SetLastTranError(env, "unable to create socket", GetLastErrorStatus()); return JDWPTRANSPORT_ERROR_IO_ERROR; } if (!SetSocketOptions(env, clientSocket)) { return JDWPTRANSPORT_ERROR_IO_ERROR; } if (attachTimeout == 0) { if (!SetSocketBlockingMode(env, clientSocket, true)) { return JDWPTRANSPORT_ERROR_IO_ERROR; } int err = connect(clientSocket, (struct sockaddr *)&serverSockAddr, sizeof(serverSockAddr)); if (err == SOCKET_ERROR) { SetLastTranError(env, "connection failed", GetLastErrorStatus()); SetSocketBlockingMode(env, clientSocket, false); return JDWPTRANSPORT_ERROR_IO_ERROR; } if (!SetSocketBlockingMode(env, clientSocket, false)) { return JDWPTRANSPORT_ERROR_IO_ERROR; } } else { if (!SetSocketBlockingMode(env, clientSocket, false)) { return JDWPTRANSPORT_ERROR_IO_ERROR; } int err = connect(clientSocket, (struct sockaddr *)&serverSockAddr, sizeof(serverSockAddr)); if (err == SOCKET_ERROR) { if (GetLastErrorStatus() != SOCKETWOULDBLOCK) { SetLastTranError(env, "connection failed", GetLastErrorStatus()); return JDWPTRANSPORT_ERROR_IO_ERROR; } else { fd_set fdwrite; FD_ZERO(&fdwrite); FD_SET(clientSocket, &fdwrite); TIMEVAL tv = {(long)(attachTimeout / 1000), (long)(attachTimeout % 1000)}; int ret = select((int)clientSocket + 1, NULL, &fdwrite, NULL, &tv); if (ret == SOCKET_ERROR) { SetLastTranError(env, "socket error", GetLastErrorStatus()); return JDWPTRANSPORT_ERROR_IO_ERROR; } if ((ret != 1) || !(FD_ISSET(clientSocket, &fdwrite))) { SetLastTranError(env, "timeout occurred", 0); return JDWPTRANSPORT_ERROR_IO_ERROR; } } } } EnterCriticalSendSection(env); EnterCriticalReadSection(env); ((internalEnv*)env->functions->reserved1)->envClientSocket = clientSocket; res = CheckHandshaking(env, clientSocket, (long)handshakeTimeout); LeaveCriticalReadSection(env); LeaveCriticalSendSection(env); if (res != JDWPTRANSPORT_ERROR_NONE) { TCPIPSocketTran_Close(env); return res; } return JDWPTRANSPORT_ERROR_NONE; } //TCPIPSocketTran_Attach
/* * ConnectHost() * args: hostname, port * purpose: bind socket and begin a non-blocking connection to * hostname at port * return: socket file descriptor if successful connect, -1 if not */ int ConnectHost(const char *hostname, unsigned int port) { struct addrinfo *res, *res_o; int socketfd; /* socket file descriptor */ char *resolved = NULL; res_o = res = LookupHostname(hostname); while (res != NULL) { resolved = ConvertHostname(res->ai_addr, res->ai_addrlen); putlog(LOG1, "Connecting to %s[%s] tcp/%d", hostname, resolved, port); if ((socketfd = socket(res->ai_family, SOCK_STREAM, 6)) == -1) { MyFree(resolved); res = res->ai_next; continue; } SetSocketOptions(socketfd); SetPort((struct sockaddr *)res->ai_addr, port); if (LocalHostName) { /* bind to virtual host */ if (bind(socketfd, (struct sockaddr *)&LocalAddr, LocalAddrSize) == -1) { char *resolved2; resolved2 = ConvertHostname((struct sockaddr *)&LocalAddr, LocalAddrSize); putlog(LOG1, "FATAL: Unable to bind virtual host %s[%s]: %s", LocalHostName, resolved2, strerror(errno)); MyFree(resolved2); } } if ((connect(socketfd, (struct sockaddr *)res->ai_addr, res->ai_addrlen)) == -1) { putlog(LOG1, "Error connecting to %s[%s] tcp/%d: %s", hostname, resolved, port, strerror(errno)); close(socketfd); MyFree(resolved); res = res->ai_next; continue; } /* nope, no error whatsoever */ freeaddrinfo(res_o); MyFree(resolved); /* not really the smartest to do... */ SetNonBlocking(socketfd); return socketfd; } if (res_o != NULL) freeaddrinfo(res_o); return -1; } /* ConnectHost() */
/* DoListen() */ void DoListen(struct PortInfo *portptr) { struct addrinfo hints; struct addrinfo *res, *res_o; int error; char port[MAXLINE]; /* can't use standard LookupHostname */ memset(&hints, 0, sizeof(hints)); hints.ai_family = PF_UNSPEC; hints.ai_socktype = SOCK_STREAM; hints.ai_flags = AI_PASSIVE; ircsprintf(port, "%d", portptr->port); error = getaddrinfo(LocalHostName, port, &hints, &res); res_o = res; if (error) { putlog(LOG1, "Unable to get local addresses, this should never happen: %s", gai_strerror(error)); return; } while (res != NULL) { if ((portptr->socket = socket(res->ai_family, SOCK_STREAM, 6)) == -1) { res = res->ai_next; portptr->socket = NOSOCKET; continue; } /* set various socket options */ SetSocketOptions(portptr->socket); SetPort((struct sockaddr *)res->ai_addr, portptr->port); if (bind(portptr->socket, res->ai_addr, res->ai_addrlen) == -1) { putlog(LOG1, "FATAL: Unable to bind port tcp/%d: %s", portptr->port, strerror(errno)); close(portptr->socket); portptr->socket = NOSOCKET; } else #ifdef SOMAXCONN if (listen(portptr->socket, SOMAXCONN) == -1) #else if (listen(portptr->socket, HYBSERV_SOMAXCONN) == -1) #endif { putlog(LOG1, "Unable to listen on port tcp/%d: %s", portptr->port, strerror(errno)); close(portptr->socket); portptr->socket = NOSOCKET; } else { putlog(LOG1, "Listener successfully started on host [%s] port tcp/%d", (LocalHostName != NULL) ? LocalHostName : "*", portptr->port); } res = res->ai_next; } portptr->tries++; if (res_o != NULL) freeaddrinfo(res_o); } /* DoListen() */
SOCKET SocketLayer::CreateBoundSocket( unsigned short port, bool blockingSocket, const char *forceHostAddress, unsigned int sleepOn10048 ) { (void) blockingSocket; int ret; SOCKET listenSocket; sockaddr_in listenerSocketAddress; // Listen on our designated Port# listenerSocketAddress.sin_port = htons( port ); #if (defined(_XBOX) || defined(_X360)) && defined(RAKNET_USE_VDP) listenSocket = socket( AF_INET, SOCK_DGRAM, IPPROTO_VDP ); #else listenSocket = socket( AF_INET, SOCK_DGRAM, 0 ); #endif if ( listenSocket == (SOCKET) -1 ) { #if defined(_WIN32) && !defined(_XBOX) && defined(_DEBUG) DWORD dwIOError = GetLastError(); LPVOID messageBuffer; FormatMessage( FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, NULL, dwIOError, MAKELANGID( LANG_NEUTRAL, SUBLANG_DEFAULT ), // Default language ( LPTSTR ) & messageBuffer, 0, NULL ); // something has gone wrong here... RAKNET_DEBUG_PRINTF( "socket(...) failed:Error code - %d\n%s", dwIOError, messageBuffer ); //Free the buffer. LocalFree( messageBuffer ); #endif return (SOCKET) -1; } SetSocketOptions(listenSocket); // Fill in the rest of the address structure listenerSocketAddress.sin_family = AF_INET; if (forceHostAddress && forceHostAddress[0]) { // printf("Force binding %s:%i\n", forceHostAddress, port); listenerSocketAddress.sin_addr.s_addr = inet_addr( forceHostAddress ); } else { // printf("Binding any on port %i\n", port); listenerSocketAddress.sin_addr.s_addr = INADDR_ANY; } // bind our name to the socket ret = bind( listenSocket, ( struct sockaddr * ) & listenerSocketAddress, sizeof( listenerSocketAddress ) ); if ( ret <= -1 ) { #if defined(_WIN32) && !defined(_XBOX) && !defined(X360) DWORD dwIOError = GetLastError(); if (dwIOError==10048) { if (sleepOn10048==0) return (SOCKET) -1; // Vista has a bug where it returns WSAEADDRINUSE (10048) if you create, shutdown, then rebind the socket port unless you wait a while first. // Wait, then rebind RakSleep(100); closesocket(listenSocket); listenerSocketAddress.sin_port = htons( port ); listenSocket = socket( AF_INET, SOCK_DGRAM, 0 ); if ( listenSocket == (SOCKET) -1 ) return false; SetSocketOptions(listenSocket); // Fill in the rest of the address structure listenerSocketAddress.sin_family = AF_INET; if (forceHostAddress && forceHostAddress[0]) listenerSocketAddress.sin_addr.s_addr = inet_addr( forceHostAddress ); else listenerSocketAddress.sin_addr.s_addr = INADDR_ANY; // bind our name to the socket ret = bind( listenSocket, ( struct sockaddr * ) & listenerSocketAddress, sizeof( listenerSocketAddress ) ); if ( ret >= 0 ) return listenSocket; } dwIOError = GetLastError(); LPVOID messageBuffer; FormatMessage( FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, NULL, dwIOError, MAKELANGID( LANG_NEUTRAL, SUBLANG_DEFAULT ), // Default language ( LPTSTR ) & messageBuffer, 0, NULL ); // something has gone wrong here... RAKNET_DEBUG_PRINTF( "bind(...) failed:Error code - %d\n%s", (unsigned int) dwIOError, (char*) messageBuffer ); //Free the buffer. LocalFree( messageBuffer ); #elif (defined(__GNUC__) || defined(__GCCXML__) || defined(_PS3) || defined(__PS3__) || defined(SN_TARGET_PS3)) && !defined(__WIN32) #endif return (SOCKET) -1; } return listenSocket; }
SOCKET SocketLayer::CreateBoundSocket( unsigned short port, bool blockingSocket, const char *forceHostAddress, unsigned int sleepOn10048 ) { (void) blockingSocket; int ret; SOCKET listenSocket; sockaddr_in listenerSocketAddress; // Listen on our designated Port# listenerSocketAddress.sin_port = htons( port ); #if (defined(_XBOX) || defined(_X360)) && defined(RAKNET_USE_VDP) listenSocket = socket( AF_INET, SOCK_DGRAM, IPPROTO_VDP ); #else listenSocket = socket( AF_INET, SOCK_DGRAM, 0 ); #endif if ( listenSocket == (SOCKET) -1 ) { #if defined(_WIN32) && !defined(_XBOX) && defined(_DEBUG) DWORD dwIOError = GetLastError(); LPVOID messageBuffer; FormatMessage( FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, NULL, dwIOError, MAKELANGID( LANG_NEUTRAL, SUBLANG_DEFAULT ), // Default language ( LPTSTR ) & messageBuffer, 0, NULL ); // something has gone wrong here... RAKNET_DEBUG_PRINTF( "socket(...) failed:Error code - %d\n%s", dwIOError, messageBuffer ); //Free the buffer. LocalFree( messageBuffer ); #endif return (SOCKET) -1; } SetSocketOptions(listenSocket); // Fill in the rest of the address structure listenerSocketAddress.sin_family = AF_INET; if (forceHostAddress && forceHostAddress[0]) { // printf("Force binding %s:%i\n", forceHostAddress, port); listenerSocketAddress.sin_addr.s_addr = inet_addr( forceHostAddress ); } else { // printf("Binding any on port %i\n", port); listenerSocketAddress.sin_addr.s_addr = INADDR_ANY; } // bind our name to the socket ret = bind( listenSocket, ( struct sockaddr * ) & listenerSocketAddress, sizeof( listenerSocketAddress ) ); if ( ret <= -1 ) { #if defined(_WIN32) && !defined(_XBOX) && !defined(X360) DWORD dwIOError = GetLastError(); if (dwIOError==10048) { if (sleepOn10048==0) return (SOCKET) -1; // Vista has a bug where it returns WSAEADDRINUSE (10048) if you create, shutdown, then rebind the socket port unless you wait a while first. // Wait, then rebind RakSleep(100); closesocket(listenSocket); listenerSocketAddress.sin_port = htons( port ); listenSocket = socket( AF_INET, SOCK_DGRAM, 0 ); if ( listenSocket == (SOCKET) -1 ) return false; SetSocketOptions(listenSocket); // Fill in the rest of the address structure listenerSocketAddress.sin_family = AF_INET; if (forceHostAddress && forceHostAddress[0]) listenerSocketAddress.sin_addr.s_addr = inet_addr( forceHostAddress ); else listenerSocketAddress.sin_addr.s_addr = INADDR_ANY; // bind our name to the socket ret = bind( listenSocket, ( struct sockaddr * ) & listenerSocketAddress, sizeof( listenerSocketAddress ) ); if ( ret >= 0 ) return listenSocket; } dwIOError = GetLastError(); LPVOID messageBuffer; FormatMessage( FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, NULL, dwIOError, MAKELANGID( LANG_NEUTRAL, SUBLANG_DEFAULT ), // Default language ( LPTSTR ) & messageBuffer, 0, NULL ); // something has gone wrong here... RAKNET_DEBUG_PRINTF( "bind(...) failed:Error code - %d\n%s", (unsigned int) dwIOError, (char*) messageBuffer ); //Free the buffer. LocalFree( messageBuffer ); #elif (defined(__GNUC__) || defined(__GCCXML__) || defined(_PS3) || defined(__PS3__) || defined(SN_TARGET_PS3)) && !defined(__WIN32) switch (ret) { case EBADF: RAKNET_DEBUG_PRINTF("bind(): sockfd is not a valid descriptor.\n"); break; #if !defined(_PS3) && !defined(__PS3__) && !defined(SN_TARGET_PS3) case ENOTSOCK: RAKNET_DEBUG_PRINTF("bind(): Argument is a descriptor for a file, not a socket.\n"); break; #endif case EINVAL: RAKNET_DEBUG_PRINTF("bind(): The addrlen is wrong, or the socket was not in the AF_UNIX family.\n"); break; case EROFS: RAKNET_DEBUG_PRINTF("bind(): The socket inode would reside on a read-only file system.\n"); break; case EFAULT: RAKNET_DEBUG_PRINTF("bind(): my_addr points outside the user's accessible address space.\n"); break; case ENAMETOOLONG: RAKNET_DEBUG_PRINTF("bind(): my_addr is too long.\n"); break; case ENOENT: RAKNET_DEBUG_PRINTF("bind(): The file does not exist.\n"); break; case ENOMEM: RAKNET_DEBUG_PRINTF("bind(): Insufficient kernel memory was available.\n"); break; case ENOTDIR: RAKNET_DEBUG_PRINTF("bind(): A component of the path prefix is not a directory.\n"); break; case EACCES: RAKNET_DEBUG_PRINTF("bind(): Search permission is denied on a component of the path prefix.\n"); break; #if !defined(_PS3) && !defined(__PS3__) && !defined(SN_TARGET_PS3) case ELOOP: RAKNET_DEBUG_PRINTF("bind(): Too many symbolic links were encountered in resolving my_addr.\n"); break; #endif default: RAKNET_DEBUG_PRINTF("Unknown bind() error %i.\n", ret); break; } #endif return (SOCKET) -1; } return listenSocket; }
TInt32 CListener::Run(TInt32 cnt) { TInt32 usedCnt = HasNewConnection(); SOCKET acceptedSocket = SOCKET_ERROR; int nLen = sizeof(SOCKADDR_IN); for (int i =0;i<usedCnt;++i) { acceptedSocket = WSAAccept(m_listeningSocket, NULL, &nLen,0,0); if (SOCKET_ERROR != acceptedSocket) { // TInt32 ret = SetSocketOptions(acceptedSocket); // if (SUCCESS > ret) // { // closesocket(ret); // continue; // } TInt32 result = SetSocketOptions(acceptedSocket); if (SUCCESS > result) { closesocket(acceptedSocket); continue; } CConnection *pNew = m_pConnectionPool->GetItem(); if (!pNew) { closesocket(acceptedSocket); return usedCnt; } CConPair pair; GetConnPair(acceptedSocket,pair); IfConnectionCallBack *pAppCallBack = m_pListenerCallBack->OnNewConnection(&pair); if (!pAppCallBack) { closesocket(acceptedSocket); continue; } IfParser *pParser; if (m_pParserFactory) { pParser = m_pParserFactory->GetParser(&pair,pNew->GetConnectionIdx()); } else { pParser = NULL; } IfCryptor *pCryptor; if (m_pCryptorFactory) { pCryptor = m_pCryptorFactory->GetCryptor(&pair,pNew->GetConnectionIdx()); } else { pCryptor = NULL; } pNew->SetConnectionType(connection_is_postive); TInt32 ret = pNew->Init(acceptedSocket,&pair,pAppCallBack,pParser,pCryptor); if (SUCCESS > ret) { pAppCallBack->OnDissconneted(ret); pNew->CloseConnection(); m_pConnectionPool->ReleaseItem(pNew); continue; } HANDLE h = CreateIoCompletionPort((HANDLE) acceptedSocket, m_compeltionPort, (ULONG_PTR)(pNew), 0); if (h != m_compeltionPort) { pAppCallBack->OnDissconneted(ret); pNew->OnDisconnected(); m_pConnectionPool->ReleaseItem(pNew); continue; } ret = pNew->OnConnected(); if (SUCCESS > ret) { pAppCallBack->OnDissconneted(ret); pNew->CloseConnection(); m_pConnectionPool->ReleaseItem(pNew); continue; } } } return usedCnt; }