int ConnectToServer(const char* server_address) { int socket_fd = socket(AF_INET, SOCK_STREAM, IPPROTO_IP); struct sockaddr_in addr; memset(&addr, 0, sizeof(addr) ); addr.sin_family = AF_INET; addr.sin_port = htons(25); if ( inet_pton(AF_INET, GetIpAddress(server_address), addr.sin_addr) == 1) { connect(socket_fd, &addr, sizeof(addr)); } return socket_fd; }
bool CNetwork_Asio::Listen() { OnListen(); tcp::endpoint endpoint(tcp::v4(), network_port_); listener_.open(endpoint.protocol()); listener_.set_option(tcp::acceptor::reuse_address(true)); listener_.non_blocking(true); listener_.bind(endpoint); listener_.listen(); log_.icprintf("Listening started on %s:%i\n", GetIpAddress().c_str(), GetPort()); active_ = true; AcceptConnection(); OnListening(); return true; }
CUserIPCheckMgr::User& CUserIPCheckMgr::GetUser( DWORD connectionIndex ) { LPCTSTR ipAddrss = GetIpAddress( connectionIndex ); for( DWORD i = 0; i < GetUserSize(); ++i ) { User& user = mUserArray[ i ]; if( 0 == _tcscmp( ipAddrss, user.mIpAddress ) ) { return user; } } static User emptyUser; return emptyUser; }
MPIPTVSOURCE_API int LeaveMulticastGroupIPv4(CLogger *logger, const TCHAR *protocolName, SOCKET m_socket, const struct sockaddr_in *source, const struct sockaddr_in *local, CParameterCollection *parameters) { ADDRINFOT *networkInterface = NULL; ADDRINFOT hints; hints.ai_family = local->sin_family; hints.ai_socktype = SOCK_DGRAM; hints.ai_protocol = IPPROTO_UDP; hints.ai_flags = AI_PASSIVE; int result = 0; if (parameters != NULL) { // we have set some parameters // get interface parameter PCParameter networkInterfaceParameter = parameters->GetParameter(INTERFACE_PARAMETER_NAME, true); if (networkInterfaceParameter != NULL) { TCHAR *networkInterfaceAddress = GetInterfaceAddress(logger, protocolName, networkInterfaceParameter->GetValue(), local->sin_family); int errorCode = GetIpAddress(networkInterfaceAddress, 0, &networkInterface, &hints); if (errorCode != 0) { logger->Log(LOGGER_ERROR, _T("%s: %s: getaddrinfo() for network interface error: %d"), protocolName, METHOD_LEAVE_MULTICAST_GROUP_IPV4_NAME, errorCode); result = -1; } if (result == 0) { logger->Log(LOGGER_INFO, _T("%s: %s: try to bind on interface '%s', address: %s"), protocolName, METHOD_LEAVE_MULTICAST_GROUP_IPV4_NAME, networkInterfaceParameter->GetValue(), networkInterfaceAddress); } FREE_MEM(networkInterfaceAddress); } } if (result == 0) { union { struct ip_mreq gr4; struct ip_mreq_source gsr4; } opt; int cmd; struct in_addr id; if (networkInterface != NULL) { id = ((sockaddr_in *)networkInterface->ai_addr)->sin_addr; } else { id.s_addr = INADDR_ANY; } socklen_t optlen; memset(&opt, 0, sizeof(opt)); if (source != NULL) { cmd = IP_DROP_SOURCE_MEMBERSHIP; opt.gsr4.imr_multiaddr = local->sin_addr; opt.gsr4.imr_sourceaddr = source->sin_addr; opt.gsr4.imr_interface = id; optlen = sizeof (opt.gsr4); } else { cmd = IP_DROP_MEMBERSHIP; opt.gr4.imr_multiaddr = local->sin_addr; opt.gr4.imr_interface = id; optlen = sizeof(opt.gr4); } logger->Log(LOGGER_INFO, METHOD_MESSAGE_FORMAT, protocolName, METHOD_LEAVE_MULTICAST_GROUP_IPV4_NAME, (source != NULL) ? _T("IP_DROP_SOURCE_MEMBERSHIP multicast request") : _T("IP_DROP_MEMBERSHIP multicast request")); result = (SetSocketOption(logger, protocolName, METHOD_LEAVE_MULTICAST_GROUP_IPV4_NAME, (source != NULL) ? _T("IP_DROP_SOURCE_MEMBERSHIP") : _T("IP_DROP_MEMBERSHIP"), m_socket, IPPROTO_IP, cmd, (char *)&opt, optlen) == 0) ? 0 : (-1); } if (networkInterface != NULL) { FreeAddrInfo(networkInterface); networkInterface = NULL; } logger->Log(LOGGER_INFO, (result == 0) ? METHOD_END_FORMAT : METHOD_END_FAIL_FORMAT, protocolName, METHOD_LEAVE_MULTICAST_GROUP_IPV4_NAME); return result; }
void CImSmtpSession::DoStateL() // performs the operation required by iState { switch (iState) { case EConnectingToSmtp: iEsmtpSpokenHere = EFalse; i8BitMimeAcceptedHere = EFalse; iSizeAcceptedHere = EFalse; iStartTlsAcceptedHere = EFalse; if(iSettings.SSLWrapper()) { // Open secure socket on port 465 for SMTP session iSocket->SSLQueueConnectL(iStatus, iSettings.ServerAddress(), iSettings.Port(), iSettings.IapPrefs(), iSettings.TlsSslDomain()); } else { // Open socket on port 25 for SMTP session iSocket->QueueConnectL(iStatus, iSettings.ServerAddress(), iSettings.Port(), iSettings.IapPrefs(), iSettings.TlsSslDomain()); } MOBILITY_TEST_MTM_STATE(iServiceId, KMobilityTestMtmStateSmtpConnectingToSmtp); break; case EWaitingForReply: iSocketIsConnected=ETrue; iSocket->QueueReceiveNextTextLine(iStatus); MOBILITY_TEST_MTM_STATE(iServiceId, KMobilityTestMtmStateSmtpWaitingForReply); break; case EAuthorisingSmtp: { TBuf8<KImskIPAddressLen> address; GetIpAddress(address); if(iRetryAuthWithHostname) { // Try sending a text string hostname instead of IP address _LIT(KDefaultNameString, "localhost"); address.Copy(KDefaultNameString); } if (iThisSession!=ESmtpSession) iSmtpBuffer.Format(KSmtpEhloCommand,&address); else iSmtpBuffer.Format(KSmtpHeloCommand,&address); iSocket->SendQueueReceive(iStatus, iSmtpBuffer); MOBILITY_TEST_MTM_STATE(iServiceId, KMobilityTestMtmStateSmtpAuthorisingSmtp); break; } case EAuthInProgress: { iSmtpAuthHelper->GetNextClientMessageL(iSmtpBuffer); iSocket->SendQueueReceive(iStatus, iSmtpBuffer); MOBILITY_TEST_MTM_STATE(iServiceId, KMobilityTestMtmStateSmtpAuthInProgress); break; } case ESendingStarttls: { // User has chosen to use Tls - send the STARTTLS cmd. iSocket->SetSSLTLSResponseL(KSmtpTlsResponse); iSocket->SendQueueReceive(iStatus, KSmtpStartTlsCommand()); MOBILITY_TEST_MTM_STATE(iServiceId, KMobilityTestMtmStateSmtpSendingStartTls); break; } case ESettingSecurity: { // Reset the Auth profiles and flags. i8BitMimeAcceptedHere = EFalse; iSizeAcceptedHere = EFalse; iStartTlsAcceptedHere = EFalse; iSupportedAuthProfiles = ENone; // Set Security, send a NOOP // and then queues asynch read request for a response // from the remote SMTP server. TBuf8<KImskIPAddressLen> address; GetIpAddress(address); iSmtpBuffer.Format(KSmtpEhloCommand, &address); iSocket->SendQueueReceive(iStatus,iSmtpBuffer); MOBILITY_TEST_MTM_STATE(iServiceId, KMobilityTestMtmStateSmtpSettingSecurity); break; } case ESendingImail: // send one Imail message SendFileL(); break; case ELogDataEvent: { if (iLogMessage) { const TInt logError = iServerEntry.Entry().iError; if (logError == KErrNone) { TBuf<KLogMaxStatusLength> status; if (iLogMessage->GetString(status, R_LOG_DEL_SENT) == KErrNone) iLogMessage->LogEvent().SetStatus(status); } iLogMessage->Start(logError, iStatus); } else { TRequestStatus* status = &iStatus; User::RequestComplete(status, KErrNone); } break; } case EResetSmtp: iSocket->SendQueueReceive(iStatus, KSmtpResetCommand()); MOBILITY_TEST_MTM_STATE(iServiceId, KMobilityTestMtmStateSmtpResetSmtp); break; case EClosingSmtp: //finished running - end SMTP session iSocket->SendQueueReceive(iStatus, KSmtpQuitCommand()); MOBILITY_TEST_MTM_STATE(iServiceId, KMobilityTestMtmStateSmtpClosingSmtp); break; default: // Unknown state gPanic(EImsmBadSessionState); break; } SetActive(); }
bool UrlReadToMemory( const string & urlString, vector< uchar > & data, map<string, string> & header ) { data.clear(); UniformResourceLocator u( urlString ); if ( u.protocol == UrlProtocol_INVALID ) { return false; } uint ip = GetIpAddress( u.hostname ); Socket sock; if ( sock.Connect( ip, u.port ) == false ) { return false; } char buf[512]; int sz; if( header.count("etag") == 0 ) { r3Sprintf( buf, "GET %s HTTP/1.1\r\nHost: %s:%d\r\n\r\n", u.path.c_str(), u.hostname.c_str(), u.port ); } else { r3Sprintf( buf, "GET %s HTTP/1.1\r\nIf-None-Match: \"%s\"\r\nHost: %s:%d\r\n\r\n", u.path.c_str(), header["etag"].c_str(), u.hostname.c_str(), u.port ); } sz = (int)strlen( buf ); Output( "Sending http request (%d chars): %s", sz, buf ); sock.Write( buf, sz ); InputStream is( sock ); // add If-None-Match with etag in the header.... int read_try_count = 5; while( read_try_count > 0 && sock.CanRead() == false ) { SleepMilliseconds( 500 ); read_try_count--; } if( read_try_count == 0 ) { Output( "Socket read for %s timed out.", urlString.c_str() ); sock.Disconnect(); return false; } HttpResponse resp ( is ); if( resp.code == 404 || resp.code == 304 ) { Output( "Http exiting read with code %d", resp.code ); sock.Disconnect(); return false; } header = resp.header; /* Output( "%s %d %s", resp.protocol.c_str(), resp.code, resp.reason.c_str() ); for( map<string, string>::iterator it = resp.header.begin(); it != resp.header.end(); ++it ) { Output( " %s: %s", it->first.c_str(), it->second.c_str() ); } */ int bytes = resp.GetInt("Content-Length"); if ( bytes > 0 ) { // not chunked - single payload int r = is.Read( bytes, data ); Output( "content length = %d, and read = %d", bytes, r ); } else if ( resp.GetString( "Transfer-Encoding" ).find( "chunked" ) != string::npos ) { // chunks while( 1 ) { string chunkHeader = is.GetLine(); if( chunkHeader.size() < 2 ) { break; } r3Sscanf( chunkHeader.c_str(), "%x", &bytes ); if( bytes > 0 ) { is.Read( bytes, data ); is.GetChar(); is.GetChar(); // skip the CRLF } else { break; } } //Output( "chunked output, abandon hope! (or implement me)"); } sock.Disconnect(); return true; }
//-------------------------------------------------------------------------- // 功能:登陆服务器列表获取 //-------------------------------------------------------------------------- KLoginServer* KLogin::GetServerList(int nRegion, int& nCount, int& nAdviceChoice) { KLoginServer* pServers = NULL; nCount = 0; nAdviceChoice = 0; if (nRegion < 0) { KIniFile* pSetting = g_UiBase.GetCommSettingFile(); if (pSetting) { pSetting->GetInteger($LOGIN, "SelServerRegion", 0, &nRegion); g_UiBase.CloseCommSettingFile(false); } } KIniFile File; int i; if (File.Load(SERVER_LIST_FILE)) { int nReadCount = 0; char szSection[32], szKey[32], szBuffer[32]; File.GetInteger("List", "RegionCount", 0, &nReadCount); //区域的数目 if (nReadCount > 0 || nRegion >= 0 && nRegion < nReadCount) { m_Choices.nServerRegionIndex = nRegion; sprintf(szSection, "Region_%d", nRegion); File.GetInteger(szSection, "Count", 0, &nReadCount); //该区域服务器的数目 if (nReadCount > 0) { pServers = (KLoginServer*)malloc(sizeof(KLoginServer) * nReadCount); if (pServers) { for (i = 0; i < nReadCount; i++) { sprintf(szKey, "%d_Address", i); if (!File.GetString(szSection, szKey, "", szBuffer, sizeof(szBuffer)) || GetIpAddress(szBuffer, pServers[nCount].Address) == false) { continue; } sprintf(szKey, "%d_Title", i); if (File.GetString(szSection, szKey, "", pServers[nCount].Title, sizeof(pServers[nCount].Title)) && pServers[nCount].Title[0]) { nCount ++; } } if (nCount == 0) { free(pServers); pServers = NULL; } } } } } if (nCount) { for (i = 0; i < nCount; i++) { if (strcmp(pServers[i].Title, m_Choices.AccountServer.Title) == 0) { nAdviceChoice = i; break; } } if (i >= nCount) strcpy(m_Choices.AccountServer.Title, pServers[nAdviceChoice].Title); m_Choices.AccountServer.Address[0] = pServers[nAdviceChoice].Address[0]; m_Choices.AccountServer.Address[1] = pServers[nAdviceChoice].Address[1]; m_Choices.AccountServer.Address[2] = pServers[nAdviceChoice].Address[2]; m_Choices.AccountServer.Address[3] = pServers[nAdviceChoice].Address[3]; } return pServers; }