//----------------------------------------------------------------------------- bool TCPSocket::connect(const NetAddress& destination) { int sd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); if (sd <= 0) { os::printf("Failed to open socket\n"); m_socket = 0; return false; } m_socket = sd; sockaddr_in address; address.sin_family = AF_INET; address.sin_addr.s_addr = htonl(destination.address()); address.sin_port = htons(destination.port()); if (::connect(sd, (const sockaddr*)&address, sizeof(sockaddr_in)) < 0) { os::printf("Failed to connect socket\n"); close(); return false; } return true; }
static shared_ptr<PixelTransferBuffer> addressToPTB(const NetAddress& addr) { std::string str = std::string("HTTP://") + addr.ipString() + ":" + format("%d", addr.port()); debugAssert(str.size() <= 28); QRcode* qrcode = encode(str.c_str(), (int)str.size()); const int N = qrcode->width; shared_ptr<PixelTransferBuffer> buffer = CPUPixelTransferBuffer::create(N, N, ImageFormat::L8()); unorm8* dst = reinterpret_cast<unorm8*>(buffer->mapWrite()); const unsigned char* src = qrcode->data; const unorm8 BLACK = unorm8::fromBits(0x00); const unorm8 WHITE = unorm8::fromBits(0xFF); for (int i = 0; i < N * N; ++i) { // The bytes are in the opposite convention dst[i] = (src[i] & 1) ? BLACK : WHITE; } dst = NULL; buffer->unmap(); QRcode_free(qrcode); return buffer; }
int TSocket::sendData( char const* data , size_t num , char const* addrName , unsigned port ) { NetAddress addr; if ( !addr.setInternet( addrName , port ) ) return false; return sendData( data , num , addr ); }
bool TSocket::connect( char const* addrName , unsigned port ) { assert( mSocketObj == INVALID_SOCKET ); NetAddress addr; if ( !addr.setInternet( addrName , port ) ) return false; return connect( addr ); }
void Robot::onConnected(Link *link, const NetAddress& localAddr, const NetAddress& peerAddr) { static int g_connectedRobotCnt = 0; ++g_connectedRobotCnt; m_link = link; if (g_connectedRobotCnt % 100 == 0) { LOG_INFO << name() << " <" << localAddr.toIpPort() << "> connect to <" << peerAddr.toIpPort() << "> success, current robot cnt = " << m_robotMgr->m_robotMap.size(); } // m_link->send("1\r\n"); }
int NetSocket::DispatchIncoming() { int length = 0; int count = 0; NetAddress from; while ((length = ReceivePacketIntern(&from))) { if (length == -1) break; INetChannel *channel = (INetChannel *)m_Channels.GetFirst(); while (channel) { if (from.Equal(channel->GetTargetAddress())) { channel->ProcessIncoming(m_Buffer, length); break; } channel = (INetChannel *)m_Channels.GetNext(); } // not found an existing channel for this address. // create a new channel if (!channel) { // do accept only connectionless (\xFF\xFF\xFF\xFF) incoming packet. if (*(int *)m_Buffer == CONNECTIONLESS_HEADER) { NetPacket *p = new NetPacket; p->time = m_System->GetTime(); p->address.FromNetAddress(&from); p->connectionless = true; p->seqnr = -1; // cut connectionless data p->data.Resize(length - 4); p->data.WriteBuf(&m_Buffer[4], length - 4); p->data.Reset(); m_IncomingPackets.AddHead(p); } } count++; } return count; }
int connect(socket_t sockfd, NetAddress &peerAddr) { const struct sockaddr_in &addr = peerAddr.getSockAddr(); int ret = ::connect(sockfd, (struct sockaddr *)&addr, static_cast<socklen_t>(sizeof addr)); return ret; }
//----------------------------------------------------------------------------- void ServerNetApplyManager::onRecvServerConncectLogin( I32 id, Char16* name, GameNetType type, U64 serverUniqueFlag, U32 serverId,U32 code ,Char8* serverVersion) { // 服务器版本验证 if (StrCmp(serverVersion,SERVER_VERSION_NUMBER)) { Char8 desc[256] = {0}; //服务器版本不一致 SServerSetting& setting = SServerSetting::getInstance(); CoreInfo* coreInfo = setting.getCoreInfo(); if (!coreInfo) { DYNAMIC_ASSERT(false); } MGStrOp::sprintf(desc,256,"版本验证错误,当前程序版本为%s,对方版本为%s",serverVersion,SERVER_VERSION_NUMBER); LoginNetPacketProcesser::getInstance().sendLoginVersionErrorInfo(id,(Char16*)coreInfo->name.c_str(),(Byte)coreInfo->type,desc,StrLen(desc)); MGStrOp::sprintf(desc,256,"版本验证错误,当前程序版本为%s,对方版本为%s",SERVER_VERSION_NUMBER,serverVersion); MG::MsgBox::show(desc,"版本验证"); return; } IServerDllInterface* serverInterface = ServerMain::getInstance().getServerDllInterface(); if (!ServerMain::getInstance().addServer(serverId,id)) { //ServerMain::getInstance().closeServer(id); //DYNAMIC_ASSERT(false); //Char16 temp[256] = {0}; //MGStrOp::sprintf(temp,256,L"有重复的服务器id,请检查%s的ServerConfig.txt文件!",name); //MG::MsgBox::show(temp,L"配置错误"); return; } NetAddress address = getAddress( getServerHandle(), id ); setConnectServerLoginState(address.getUin(),id,true,true); //MG_LOG(out_error,"onLogin %s %d \n",address.getIPStr(),address.getPort()); Sleep(5); serverInterface->onServerConnected( id, type, serverId, serverUniqueFlag, &address ); I32 len = WStrLen(name); Char16* postName = MG_NEW Char16[MAX_SERVER_NAME_LEN]; WStrnCpyS(postName,MAX_SERVER_NAME_LEN,name,len); NetAddress* postAddr = new NetAddress(address); ::PostMessage(ServerMain::getInstance().getDialogHandle(),LAUNCH_SERVER_CONNECT,(WPARAM)postName,(LPARAM)postAddr); }
bool TSocket::connect( NetAddress const& addr ) { if ( !createTCP( true ) ) { return false; } int result = ::connect( getSocketObject() , (sockaddr*)&addr.get() , sizeof( addr.get() ) ); if ( result == SOCKET_ERROR && WSAGetLastError() != WSAEWOULDBLOCK ) { socketError("Failed connect()"); return false; } mState = SKS_CONNECTING; return true; }
bool bindAddress(socket_t sockfd, const NetAddress& localaddr) { int ret = bind(sockfd, (struct sockaddr *)&localaddr.m_addr, sizeof(localaddr.m_addr)); if(ret == SOCKET_ERROR) { LOG_SYSTEM_ERR << "bindAddress failed address=<" << localaddr.toIpPort() << ">"; return false; } return true; }
Boolean SIPClient::processURL(char const* url) { do { // If we don't already have a server address/port, then // get these by parsing the URL: if (fServerAddress.s_addr == 0) { NetAddress destAddress; if (!parseSIPURL(envir(), url, destAddress, fServerPortNum)) break; fServerAddress.s_addr = *(unsigned*)(destAddress.data()); if (fOurSocket != NULL) { fOurSocket->changeDestinationParameters(fServerAddress, fServerPortNum, 255); } } return True; } while (0); return False; }
char* getSDPDescriptionFromURL(Medium* client, char const* url, char const* username, char const* password, char const* proxyServerName, unsigned short proxyServerPortNum, unsigned short clientStartPortNum) { SIPClient* sipClient = (SIPClient*)client; if (proxyServerName != NULL) { // Tell the SIP client about the proxy: NetAddressList addresses(proxyServerName); if (addresses.numAddresses() == 0) { client->envir() << "Failed to find network address for \"" << proxyServerName << "\"\n"; } else { NetAddress address = *(addresses.firstAddress()); unsigned proxyServerAddress // later, allow for IPv6 ##### = *(unsigned*)(address.data()); if (proxyServerPortNum == 0) proxyServerPortNum = 5060; // default sipClient->setProxyServer(proxyServerAddress, proxyServerPortNum); } } if (clientStartPortNum == 0) clientStartPortNum = 8000; // default sipClient->setClientStartPortNum(clientStartPortNum); char* result; if (username != NULL && password != NULL) { result = sipClient->inviteWithPassword(url, username, password); } else { result = sipClient->invite(url); } extern unsigned statusCode; statusCode = sipClient->inviteStatus(); return result; }
void AllocAddressesForHost(NetAddresses& addressesToAllocTo, std::string& host_name, const std::string& service){ addrinfo hints; addrinfo* addr; if (host_name == ""){ host_name = "local_host"; } //which network layer it's using memset(&hints, 0, sizeof(hints)); //sets all hints to 0 hints.ai_family = AF_INET; hints.ai_socktype = SOCK_STREAM; // stream based, determines transport layer TCP hints.ai_flags = AI_PASSIVE; // used for binding/listening int status = getaddrinfo(host_name.c_str(), service.c_str(), &hints, &addr); if (status != 0) { //printf("Failed to create socket address! %s\n", gai_strerror(status)); } addrinfo *iter; for (iter = addr; iter != nullptr; iter = iter->ai_next) { GetInAddress(iter->ai_addr); //instantiate address NetAddress newOutAddress; newOutAddress.Init(iter->ai_addr, iter->ai_addrlen); addressesToAllocTo.push_back(newOutAddress); } freeaddrinfo(addr); }
void getSDPDescription(RTSPClient::responseHandler* afterFunc) { extern char* proxyServerName; if (proxyServerName != NULL) { // Tell the SIP client about the proxy: NetAddressList addresses(proxyServerName); if (addresses.numAddresses() == 0) { ourSIPClient->envir() << "Failed to find network address for \"" << proxyServerName << "\"\n"; } else { NetAddress address = *(addresses.firstAddress()); unsigned proxyServerAddress // later, allow for IPv6 ##### = *(unsigned*)(address.data()); extern unsigned short proxyServerPortNum; if (proxyServerPortNum == 0) proxyServerPortNum = 5060; // default ourSIPClient->setProxyServer(proxyServerAddress, proxyServerPortNum); } } extern unsigned short desiredPortNum; unsigned short clientStartPortNum = desiredPortNum; if (clientStartPortNum == 0) clientStartPortNum = 8000; // default ourSIPClient->setClientStartPortNum(clientStartPortNum); extern char const* streamURL; char const* username = ourAuthenticator == NULL ? NULL : ourAuthenticator->username(); char const* password = ourAuthenticator == NULL ? NULL : ourAuthenticator->password(); char* result; if (username != NULL && password != NULL) { result = ourSIPClient->inviteWithPassword(streamURL, username, password); } else { result = ourSIPClient->invite(streamURL); } int resultCode = result == NULL ? -1 : 0; afterFunc(NULL, resultCode, strDup(result)); }
void Robot::onDisconnect(Link *link, const NetAddress& localAddr, const NetAddress& peerAddr) { /* if (link->m_isCreateByConnector) { Robot *robot = m_robotMgr->createRobot(); m_robotMgr->m_wan.connect(peerAddr.toIp(), peerAddr.toPort(), *robot); } */ if (m_robotMgr->m_robotMap.size() - 1 % 100 >= 0) { LOG_INFO << "robot<" << m_robotId << "> <" << localAddr.toIpPort() << "> to gateserver <" << peerAddr.toIpPort() << "> closed! current robot cnt = " << m_robotMgr->m_robotMap.size() - 1; } m_robotMgr->onRobotDisconnect(this); }
///Send data to the address specified. Returns the number of bytes sent. int UDPSocket::SendTo( const NetAddress &remote, const IProtocol *protocol ) throw ( Error ) { ///Clear out the stream for data to be sent. sstream.Clear(); //Use the protocol to format the pack about to be sent. int size = protocol->FormatPacket(sstream); int ret = sendto(socket, sstream.GetBuffer(), size, 0, remote, remote.Size()); if (ret == SOCKET_ERROR) { if ( !blocking && WSAGetLastError() == WSAEWOULDBLOCK ) return ret; // would have blocked ///Something really went wrong. ThrowError(Error::E_SocketError); } return ret; }
///Receive Data on the socket. Stores the address of the sender in address. ///Returns a list of the messages extracted from the buffer. Users must delete list. int UDPSocket::RecvFrom( NetAddress &remote ) throw ( Error ) { ///Clear out the stream for data to be sent. rstream.Clear(); int size = remote.Size(); int ret = recvfrom(socket, rstream.GetBuffer(), rstream.Capacity(), 0, remote, &size); if (ret == SOCKET_ERROR) { if ( !blocking && WSAGetLastError() == WSAEWOULDBLOCK ) return 0; // would have blocked ///Something really went wrong. ThrowError(Error::E_SocketError); } //rstream.SetWriteIndex(ret); ///Return the number of bytes received. return ret; }
NetAddress::NetAddress(NetAddress const& orig) { assign(orig.data(), orig.length()); }
bool CClientSession::StartCS( NetAddress& stConnectionAddr ) { LPSTR lpszAddr = stConnectionAddr.ToString(); // The size of buffer in NetAddress type : 20 if( strnlen( lpszAddr, 20 ) >= 20 || stConnectionAddr.port <= 0 ) return false; if( m_Session.StartP() == FALSE ) { TLOG( LOG_DEBUG, _T( "[ERROR] Failed to initialize the object as CPeer type." ) ); return false; } if( m_Session.CreateNBOLSocket() == FALSE ) { TLOG( LOG_DEBUG, _T( "[ERROR] Failed to create the socket." ) ); return false; } if( CWSAEventSelect::WSAESBegin( m_Session.GetNSocket() ) == false ) { TLOG( LOG_DEBUG, _T( "[ERROR] Failed to create the WSAEventSelect model." ) ); return false; } if( sizeof( TCHAR ) == sizeof( WCHAR ) ) { WCHAR szAddress[20] = {0,}; MultiByteToWideChar( CP_ACP, MB_PRECOMPOSED, lpszAddr, -1, szAddress, 20 ); TLOG( LOG_CRT, _T( "Connecting to the %s:%d..." ), szAddress, stConnectionAddr.port ); } else TLOG( LOG_CRT, _T( "Connecting to the %s:%d..." ), lpszAddr, stConnectionAddr.port ); if( m_Session.CreateConnection( lpszAddr, stConnectionAddr.port ) == false ) { TLOG( LOG_DEBUG, _T( "[ERROR] Failed to connect the opposite side." ) ); return false; } m_hOperatingEventOfCS = CreateEvent( NULL, FALSE, FALSE, NULL ); if( m_hOperatingEventOfCS == NULL ) { DWORD dwErrNo = GetLastError(); TLOG( LOG_DEBUG, _T( "[ERROR] Need to check. ErrNo.%d" ), dwErrNo ); } SetConsoleCtrlHandler( ClientConnectionHandler, TRUE ); { WaitForSingleObject( m_hOperatingEventOfCS, WAIT_TIMEOUT_INTERVAL ); CloseHandle( m_hOperatingEventOfCS ); m_hOperatingEventOfCS = NULL; } SetConsoleCtrlHandler( ClientConnectionHandler, FALSE ); if( m_IsConnection == false ) { TLOG( LOG_DEBUG, _T( "Connection failed!!" ) ); return false; } return true; }
// FinishInitialization status_t InsecureConnection::FinishInitialization() { PRINT(("InsecureConnection::FinishInitialization()\n")); // get the down stream channel InsecureChannel* channel = dynamic_cast<InsecureChannel*>(DownStreamChannelAt(0)); if (!channel) return B_BAD_VALUE; // receive the connect request ConnectRequest request; status_t error = channel->Receive(&request, sizeof(ConnectRequest)); if (error != B_OK) return error; // check the protocol version int32 protocolVersion = B_BENDIAN_TO_HOST_INT32(request.protocolVersion); if (protocolVersion != kProtocolVersion) { _SendErrorReply(channel, B_ERROR); return B_ERROR; } // get our address (we need it for binding) in_addr serverAddr; serverAddr.s_addr = request.serverAddress; // check number of up and down stream channels int32 upStreamChannels = B_BENDIAN_TO_HOST_INT32(request.upStreamChannels); int32 downStreamChannels = B_BENDIAN_TO_HOST_INT32( request.downStreamChannels); if (upStreamChannels < kMinUpStreamChannels) upStreamChannels = kMinUpStreamChannels; else if (upStreamChannels > kMaxUpStreamChannels) upStreamChannels = kMaxUpStreamChannels; if (downStreamChannels < kMinDownStreamChannels) downStreamChannels = kMinDownStreamChannels; else if (downStreamChannels > kMaxDownStreamChannels) downStreamChannels = kMaxDownStreamChannels; // due to a bug on BONE we have a maximum of 2 working connections // accepted on one listener socket. NetAddress peerAddress; if (channel->GetPeerAddress(&peerAddress) == B_OK && peerAddress.IsLocal()) { upStreamChannels = 1; if (downStreamChannels > 2) downStreamChannels = 2; } int32 allChannels = upStreamChannels + downStreamChannels; // create a listener socket int fd = socket(AF_INET, SOCK_STREAM, 0); if (fd < 0) { error = errno; _SendErrorReply(channel, error); return error; } SocketCloser _(fd); // bind it to some port sockaddr_in addr; addr.sin_family = AF_INET; addr.sin_port = 0; addr.sin_addr = serverAddr; if (bind(fd, (sockaddr*)&addr, sizeof(addr)) < 0) { error = errno; _SendErrorReply(channel, error); return error; } // get the port int addrSize = sizeof(addr); if (getsockname(fd, (sockaddr*)&addr, &addrSize) < 0) { error = errno; _SendErrorReply(channel, error); return error; } // set socket to non-blocking int dontBlock = 1; if (setsockopt(fd, SOL_SOCKET, SO_NONBLOCK, &dontBlock, sizeof(int)) < 0) { error = errno; _SendErrorReply(channel, error); return error; } // start listening if (listen(fd, allChannels - 1) < 0) { error = errno; _SendErrorReply(channel, error); return error; } // send the reply ConnectReply reply; reply.error = B_HOST_TO_BENDIAN_INT32(B_OK); reply.upStreamChannels = B_HOST_TO_BENDIAN_INT32(upStreamChannels); reply.downStreamChannels = B_HOST_TO_BENDIAN_INT32(downStreamChannels); reply.port = addr.sin_port; error = channel->Send(&reply, sizeof(ConnectReply)); if (error != B_OK) return error; // start accepting bigtime_t startAccepting = system_time(); for (int32 i = 1; i < allChannels; ) { // accept a connection int channelFD = accept(fd, NULL, 0); if (channelFD < 0) { error = errno; if (error == B_INTERRUPTED) { error = B_OK; continue; } if (error == B_WOULD_BLOCK) { bigtime_t now = system_time(); if (now - startAccepting > kAcceptingTimeout) RETURN_ERROR(B_TIMED_OUT); snooze(10000); continue; } RETURN_ERROR(error); } PRINT((" accepting channel %ld\n", i)); // create a channel channel = new(nothrow) InsecureChannel(channelFD); if (!channel) { closesocket(channelFD); return B_NO_MEMORY; } // add it if (i < upStreamChannels) // inverse, since we are on server side error = AddDownStreamChannel(channel); else error = AddUpStreamChannel(channel); if (error != B_OK) { delete channel; return error; } i++; startAccepting = system_time(); } return B_OK; }
// Init (client side) status_t InsecureConnection::Init(const char* parameters) { PRINT(("InsecureConnection::Init\n")); if (!parameters) return B_BAD_VALUE; status_t error = AbstractConnection::Init(); if (error != B_OK) return error; // parse the parameters to get a server name and a port we shall connect to // parameter format is "<server>[:port] [ <up> [ <down> ] ]" char server[256]; uint16 port = kDefaultInsecureConnectionPort; int upStreamChannels = kDefaultUpStreamChannels; int downStreamChannels = kDefaultDownStreamChannels; if (strchr(parameters, ':')) { int result = sscanf(parameters, "%255[^:]:%hu %d %d", server, &port, &upStreamChannels, &downStreamChannels); if (result < 2) return B_BAD_VALUE; } else { int result = sscanf(parameters, "%255[^:] %d %d", server, &upStreamChannels, &downStreamChannels); if (result < 1) return B_BAD_VALUE; } // resolve server address NetAddress netAddress; error = NetAddressResolver().GetHostAddress(server, &netAddress); if (error != B_OK) return error; in_addr serverAddr = netAddress.GetAddress().sin_addr; // open the initial channel Channel* channel; error = _OpenClientChannel(serverAddr, port, &channel); if (error != B_OK) return error; error = AddUpStreamChannel(channel); if (error != B_OK) { delete channel; return error; } // send the server a connect request ConnectRequest request; request.protocolVersion = B_HOST_TO_BENDIAN_INT32(kProtocolVersion); request.serverAddress = serverAddr.s_addr; request.upStreamChannels = B_HOST_TO_BENDIAN_INT32(upStreamChannels); request.downStreamChannels = B_HOST_TO_BENDIAN_INT32(downStreamChannels); error = channel->Send(&request, sizeof(ConnectRequest)); if (error != B_OK) return error; // get the server reply ConnectReply reply; error = channel->Receive(&reply, sizeof(ConnectReply)); if (error != B_OK) return error; error = B_BENDIAN_TO_HOST_INT32(reply.error); if (error != B_OK) return error; upStreamChannels = B_BENDIAN_TO_HOST_INT32(reply.upStreamChannels); downStreamChannels = B_BENDIAN_TO_HOST_INT32(reply.downStreamChannels); port = B_BENDIAN_TO_HOST_INT16(reply.port); // open the remaining channels int32 allChannels = upStreamChannels + downStreamChannels; for (int32 i = 1; i < allChannels; i++) { PRINT((" creating channel %ld\n", i)); // open the channel error = _OpenClientChannel(serverAddr, port, &channel); if (error != B_OK) RETURN_ERROR(error); // add it if (i < upStreamChannels) error = AddUpStreamChannel(channel); else error = AddDownStreamChannel(channel); if (error != B_OK) { delete channel; return error; } } return B_OK; }