bool Email::sendEmail( const std::string &smtpServer, u16 port, const std::string &from, const std::string &to, const std::string &subject, const std::string &body, const std::string &attachedFile /*= ""*/, bool onlyCheck /*= false */ ) { bool ok = false; TCPSocket sock; Address ad(smtpServer, port); sock.connect(ad); if (sock.connected()) { // we must skip the first line std::string formatedBody = "\r\n"; if(!sendEMailCommand (sock, "", 220)) goto end; if(onlyCheck) { if(!sendEMailCommand (sock, "HELO localhost")) goto end; if(!sendEMailCommand (sock, "MAIL FROM: " + from)) goto end; if(!sendEMailCommand (sock, "RCPT TO: " + to)) goto end; if(!sendEMailCommand (sock, "QUIT", 221)) goto end; ok = true; } else { if(!sendEMailCommand (sock, "HELO localhost")) goto end; //if(!sendEMailCommand (sock, "STARTTLS", 220)) goto end; //if(!sendEMailCommand (sock, "AUTH PLAIN AHVzZXIAc2VjcmV0")) goto end; if(!sendEMailCommand (sock, "AUTH LOGIN", 334)) goto end; if(!sendEMailCommand (sock, "bccr001")) goto end; if(!sendEMailCommand (sock, "MAIL FROM: " + from)) goto end; if(!sendEMailCommand (sock, "RCPT TO: " + to)) goto end; if(!sendEMailCommand (sock, "DATA", 354)) goto end; std::string buffer = "From: " + from + "\r\n" "To: " + to + "\r\n" "Subject: " + subject + "\r\n" + formatedBody + "\r\n."; if(!sendEMailCommand (sock, buffer)) goto end; if(!sendEMailCommand (sock, "QUIT", 221)) goto end; ok = true; } end: sock.close(); } else { MessageBox(NULL, smtpServer.c_str(), "woops", MB_OK); } return ok; }
int main(int argc, char** argv){ char* hname; char* sname; debug_lib::init(argv[0]); if ( argc == 2 ){ hname = NULL; sname = argv[1]; }else if ( argc == 3 ){ hname = argv[1]; sname = argv[2]; }else{ debug_lib::log( "exit: wrong arguments passed %d\n", argc ); print_help(); exit(1); } try{ TCPServerSocket* sock = new TCPServerSocket(); sock->bind(hname, sname); sock->listen(); do{ while( true ){ TCPSocket* acceptsock = sock->accept(); MessageFramer* framer = new FixedLenFramer(sizeof(nowait_struct)); TCPAcceptSocketNoWait* acceptsocknw = new TCPAcceptSocketNoWait( acceptsock->getFd(), framer); Message msg; msg.setFramer(framer); struct nowait_struct stmsg; strcpy( stmsg.str, "hello world in a structure" ); msg.putDataRaw( (char*)&stmsg, sizeof(nowait_struct) ); acceptsocknw->send( msg ); //delete only closes the socket from the server side. The socket is still open on the client side. delete acceptsock; delete framer; delete acceptsocknw; } } while(1); }catch(debug_lib::Exception& e){ debug_lib::log( "exit due to error in server: %s", e.what()); exit(1); }catch(...){ debug_lib::log( "exit due to error in server: %s", "unknown error" ); exit(1); } return 0; }
Task* CRTConnListener::GetSessionTask(int osSocket, struct sockaddr_in* addr) { TCPSocket* theSocket = NULL; Assert(osSocket != EventContext::kInvalidFileDesc); // when the server is behing a round robin DNS, the client needs to knwo the IP address ot the server // so that it can direct the "POST" half of the connection to the same machine when tunnelling RTSP thru HTTP CRTConnection* theTask = new CRTConnection(); if(NULL == theTask) return NULL; theSocket = theTask->GetSocket(); // out socket is not attached to a unix socket yet. //set options on the socket int sndBufSize = 96L * 1024L; theSocket->Set(osSocket, addr); theSocket->InitNonBlocking(osSocket); //we are a server, always disable nagle algorithm theSocket->NoDelay(); theSocket->KeepAlive(); theSocket->SetSocketBufSize(sndBufSize); //setup the socket. When there is data on the socket, //theTask will get an kReadEvent event theSocket->RequestEvent(EV_RE); theTask->SetTimer(30*1000); StrPtrLen* remoteStr = theSocket->GetRemoteAddrStr(); LI("CRTConnListener Get a connection,ip:%.*s port:%d \n",remoteStr->Len, remoteStr->Ptr, ntohs(addr->sin_port)); this->RunNormal(); return theTask; }
void LRTGroupSession::Init() { TCPSocket* socket = this->GetSocket(); socket->Open(); socket->InitNonBlocking(socket->GetSocketFD()); socket->NoDelay(); socket->KeepAlive(); socket->SetSocketBufSize(96L * 1024L); socket->SetTask(this); this->SetTimer(120*1000); for(int i=0;i<MSG_PACKED_ONCE_NUM;++i) { m_packedNewMsg.add_msgs(); } for(int i=0;i<MSG_PACKED_ONCE_NUM;++i) { m_packedSeqnMsg.add_msgs(); } for(int i=0;i<MSG_PACKED_ONCE_NUM;++i) { m_packedDataMsg.add_msgs(); } }
void TCPSOCKET_OPEN_CLOSE_REPEAT() { SKIP_IF_TCP_UNSUPPORTED(); TCPSocket *sock = new TCPSocket; if (!sock) { TEST_FAIL(); } for (int i = 0; i < 2; i++) { TEST_ASSERT_EQUAL(NSAPI_ERROR_OK, sock->open(NetworkInterface::get_default_instance())); TEST_ASSERT_EQUAL(NSAPI_ERROR_OK, sock->close()); } delete sock; }
static nsapi_error_t _tcpsocket_connect_to_chargen_srv(TCPSocket &sock) { SocketAddress tcp_addr; get_interface()->gethostbyname(MBED_CONF_APP_ECHO_SERVER_ADDR, &tcp_addr); tcp_addr.set_port(19); nsapi_error_t err = sock.open(get_interface()); if (err != NSAPI_ERROR_OK) { return err; } return sock.connect(tcp_addr); }
void TCPSOCKET_RECV_100K() { TCPSocket sock; _tcpsocket_connect_to_chargen_srv(sock); Timer timer; timer.start(); rcv_n_chk_against_rfc864_pattern(sock); timer.stop(); TEST_ASSERT_EQUAL(NSAPI_ERROR_OK, sock.close()); printf("MBED: Time taken: %fs\n", timer.read()); }
void TCPMessengerServer::run() { m_isRunning = true; m_dispatcher = new PeersRequestsDispatcher(this); m_dispatcher->start(); while (m_isRunning) { TCPSocket* peerSocket = m_tcpServerSocket->listenAndAccept(); if (peerSocket != NULL) { cout << "new peer connected: " << peerSocket->GetDestIpAndPort() << endl; m_openedPeers[peerSocket->GetDestIpAndPort()] = peerSocket; } } }
void MsaTcpServer::run() { _dispatcher->start(); while(true) { TCPSocket* newPeer = _serverSock->listenAndAccept(); if (newPeer!= NULL) { cout<<"Add Peer"<<newPeer->destIpAndPort()<<endl; _dispatcher->addPeer(newPeer); } } }
TCPSocket* MultipleTCPSocketsListener::listenToSocket() { if (sockets.empty()) { return NULL; } // create local set for the select function (fd_set) fd_set readFd; FD_ZERO(&readFd); // fill the set with file descriptors from the socket list using (FD_SET macro) int biggestSocket = 0; for (unsigned int i = 0; i < this->sockets.size(); i++) { int currentFd = this->sockets[i]->getSocketFd(); FD_SET(currentFd, &readFd); if (currentFd > biggestSocket) { biggestSocket = currentFd; } } struct timeval timeout; timeout.tv_sec = TIMEOUT; timeout.tv_usec = 0; int numOfActiveFds = select(biggestSocket + 1, &readFd, NULL, NULL, &timeout); TCPSocket* activeClient = NULL; if (numOfActiveFds > 0) { for (unsigned int i = 0; i < this->sockets.size(); i++) { TCPSocket* currentSocket = this->sockets[i]; if (FD_ISSET(currentSocket->getSocketFd(), &readFd)) { cout << "Incoming from : " << currentSocket->getClientAsString() << endl; activeClient = currentSocket; break; } } } // if select return a valid socket return the matching TCPSocket object otherwise return NULL return activeClient; }
SocketPort::SocketPort(SocketService *svc, TCPSocket &tcp) : Socket(accept(tcp.getSocket(), NULL, NULL)) { detect_pending = true; detect_output = false; detect_disconnect = true; #ifdef WIN32 // FIXME: error handling event = CreateEvent(NULL,TRUE,FALSE,NULL); #endif next = prev = NULL; service = NULL; // FIXME: use macro here and in other files... #ifndef WIN32 if(so > -1) #else if(so != INVALID_SOCKET) #endif { setError(false); if( svc ) svc->attach(this); } }
int main() { TCPSocket socket; socket.connect("169.254.0.10", 10001); boost::thread requisicoes1(fazRequisicoes, &socket, "8", .2); boost::thread requisicoes2(fazRequisicoes, &socket, "5", .2); boost::thread requisicoes3(fazRequisicoes, &socket, "I", 1); boost::thread leitura(recebeRequisicoes, &socket); while(1); printf("finalizou a thread principal\n"); return 0; }
void rcv_n_chk_against_rfc864_pattern_nonblock(TCPSocket &sock) { static const size_t total_size = 1024 * 100; static const size_t buff_size = 1220; uint8_t buff[buff_size]; size_t recvd_size = 0; int time_allotted = split2half_rmng_tcp_test_time(); // [s] Timer timer; timer.start(); // Verify received data while (recvd_size < total_size) { int rd = sock.recv(buff, buff_size); TEST_ASSERT(rd > 0 || rd == NSAPI_ERROR_WOULD_BLOCK); if (rd > 0) { check_RFC_864_pattern(buff, rd, recvd_size); recvd_size += rd; } else if (rd == NSAPI_ERROR_WOULD_BLOCK) { if (timer.read() >= time_allotted) { TEST_FAIL(); break; } TEST_ASSERT_NOT_EQUAL(osEventTimeout, osSignalWait(SIGNAL_SIGIO, SIGIO_TIMEOUT).status); } else { TEST_FAIL(); break; } } timer.stop(); printf("MBED: Time taken: %fs\n", timer.read()); }
/*-----TCPSocket::ReceiveConnection-------------------------------------------- * Called to set up a given TCPSocket from an incoming connection on the * current TCPSocket *---------------------------------------------------------------------------*/ bool TCPSocket::RecvConnection(TCPSocket &newSocket) { socklen_t sizeofSockaddr = sizeof(myRemoteAddrStorage); bool success = false; // Make sure we stay under FD_SETSIZE // See: // * http://www.securityfocus.com/archive/1/490711 // * http://securityvulns.com/docs7669.html // for more details // This probably has no affect, since we are using multiple threads, but keep it here // to be used as a sanity check. int newDesc = accept(myDescriptor, (struct sockaddr*)&newSocket.myRemoteAddr, &sizeofSockaddr); if (newDesc < 0) { // Something went wrong, probably indicates an error somewhere else gLog.warning(tr("Cannot accept new connection:\n%s"), strerror(errno)); return false; } if (newDesc < static_cast<int>(FD_SETSIZE)) { newSocket.myDescriptor = newDesc; newSocket.SetLocalAddress(); success = true; } else { gLog.error(tr("Cannot accept new connection, too many descriptors in use.")); close(newDesc); } return success; }
void TCPSOCKET_RECV_100K_NONBLOCK() { TCPSocket sock; _tcpsocket_connect_to_chargen_srv(sock); sock.set_blocking(false); sock.sigio(callback(_sigio_handler, Thread::gettid())); Timer timer; timer.start(); rcv_n_chk_against_rfc864_pattern_nonblock(sock); timer.stop(); TEST_ASSERT_EQUAL(NSAPI_ERROR_OK, sock.close()); printf("MBED: Time taken: %fs\n", timer.read()); }
void TLSSocket::Handshake(TCPSocket& socket, HandshakeRole role, TLSSocket* reuse) { SSL_CTX* ctx = role == Client ? TLSClientContext::Get() : TLSServerContext::Get(); if (!ctx) throw TLSError("TLS context not initialised."); session = SSL_new(ctx); if (!session) throw TLSProtocolError(); if (SSL_set_fd(session, socket.Socket()) != 1) throw TLSProtocolError(); if (reuse) { assert(reuse->session); SSL_copy_session_id(session, reuse->session); } if (role == Client) SSL_set_connect_state(session); else SSL_set_accept_state(session); int result; while (true) { if (role == Client) result = SSL_connect(session); else result = SSL_accept(session); boost::this_thread::interruption_point(); if (result == 1) break; else EvaluateResult(result); } }
// Accepts an incoming connection int TCPServer::Accept(TCPSocket &outsock, char* ipAddr, bool nonBlocking) const { if (!m_isRunning) { std::cerr << "Start() must be called before Accept()." << std::endl; return 1; } sockaddr_in sockaddrIn; int addrlen = sizeof(sockaddrIn); SOCKET insock = accept(m_socket, (sockaddr*)&sockaddrIn, &addrlen); if (insock == INVALID_SOCKET) { int err = WSAGetLastError(); if (err != WSAEWOULDBLOCK || m_isBlocking) { std::cerr << "accept() failed: " << err << std::endl; } return 1; } outsock.m_socket = insock; outsock.m_isConnected = true; outsock.SetBlocking(!nonBlocking); inet_ntop(AF_INET, &sockaddrIn.sin_addr, ipAddr, INET_ADDRSTRLEN); return 0; }
void Dispatcher::openSession(TCPSocket* peer, const string& data){ if (isLoggedIn(peer)){ if (loggedInUsers.find(data) != loggedInUsers.end()) { TCPSocket *peerB = loggedInUsers[data]; // find second peer according to the data //if peer was found and client did not open session with himself then allow session if ((peerB != NULL && peer != peerB) && !(std::find(peers.begin(),peers.end(),peerB) == peers.end())) { //get the username from the peers string peerName, peerBName; for (map<string, TCPSocket *>::iterator itr = loggedInUsers.begin(); itr != loggedInUsers.end(); ++itr) { if (itr->second == peer) { peerName = itr->first; } if (itr->second == peerB) { peerBName = itr->first; } } //tell peerB to change sessionIsActive=true TCPMessengerProtocol::sendToServer(SESSION_ESTABLISHED, peerBName + " " + peerB->fromAddr(), peer); TCPMessengerProtocol::sendToServer(SESSION_ESTABLISHED, peerName + " " + peer->fromAddr(), peerB); //remove peers from the dispatcher responsibility this->removePeer(peer); this->removePeer(peerB); //give responsibility of the peers to a new brocker Brocker *broker = new Brocker(this, peer, peerB, peerName, peerBName); //keep reference of brocker in brockers vector brockers.push_back(broker); } else { //get peer name string peerName; for (map<string, TCPSocket *>::iterator itr = loggedInUsers.begin(); itr != loggedInUsers.end(); ++itr) { if (itr->second == peer) { peerName = itr->first; } } //if peer does not exist in peers list - refuse the session TCPMessengerProtocol::sendToServer(SESSION_REFUSED, peerName, peer); } } } }
bool TCPConnection::sendMessageFirstSizeInInt(string ip, string text, int port) { try { TCPSocket *sock = new TCPSocket(ip, port); uint32_t size = htonl(strlen(text.c_str())); //sent packet size sock->send(&size, sizeof(size)); //sent packet itself sock->send(text.c_str(), size); delete sock; return true; } catch (SocketException &e) { cerr << e.what() << endl; return false; } return false; }
int main() { TCPSocket* sock = new TCPSocket(); sock->setHomeAddr( "127.0.0.1", 8023); sock->setRemoteAddr( "127.0.0.1", 8026); sock->Connect(); cout << "accepted" << endl; cout << sock->getRemoteAddr()->getIp() << endl; while(1); delete sock; return 0; }
void TCPSOCKET_RECV_100K_NONBLOCK() { TCPSocket sock; nsapi_error_t err = _tcpsocket_connect_to_chargen_srv(sock); if (err != NSAPI_ERROR_OK) { TEST_FAIL(); return; } sock.set_blocking(false); sock.sigio(callback(_sigio_handler, Thread::gettid())); rcv_n_chk_against_rfc864_pattern_nonblock(sock); TEST_ASSERT_EQUAL(NSAPI_ERROR_OK, sock.close()); }
int main(int argc, char* argv[]) { // define Arguments and Application variables define_args(); // parse Arguments if (A.parseArgs(argc, argv) == false) { A.printArgs(); exit(EXIT_FAILURE); } // print Help if (A.getParam<bool>("p_help") == true) { A.printArgs(); exit(EXIT_SUCCESS); } TCPClient* client = new TCPClient(); TCPSocket* socket = client->connect(A.getParam<const char*>("p_server"), A.getParam<int>("p_port")); if (socket != NULL) { // build message std::string message(A.getArg(0)); for (size_t i = 1; i < A.numArg(); i++) { message += " "; message += A.getArg(i); } socket->send(message.c_str(), message.size()); char data[1024]; size_t datalen; datalen = socket->recv(data, sizeof(data)-1); data[datalen] = '\0'; std::cout << data; delete socket; } delete client; return 0; }
int BasicTCPServer::WorkerThread::ThreadBody() { InternetAddress addr; TCPSocket sock; ActionStatus st = m_pServer->m_Listener.Accept(&sock, &addr); if (st.Successful() && sock.Valid()) { m_pServer->m_ActiveThreadCount++; WorkerThread *pThread = new WorkerThread(m_pServer); if (!pThread || !pThread->Start()) delete pThread; m_pServer->ConnectionHandler(sock, addr); } if (!--m_pServer->m_ActiveThreadCount) m_pServer->m_LastThreadDone.Set(); return 0; }
//acceptor模块调用GetSessionTask函数,创建一个连接会话,处理该socket句柄上的所有任务。 Task* ApsAppTcpListenerSocket::GetSessionTask(int osSocket, struct sockaddr_in* addr) { Assert(osSocket != EventContext::kInvalidFileDesc); TCPSocket* theSocket = NULL; //new one web accept session ApsAppSrvSession* theTask = new ApsAppSrvSession(); ApsLogger::Debug("New PushClientSession, socket fd = %d task = %p!",osSocket,theTask); if(NULL == theTask)//no enough memory, TCPListenerSocket will close the socket! { ApsLogger::Debug("PushClientSession create error: no memory!"); return NULL; } theSocket = theTask->GetSocket(); // out socket is not attached to a unix socket yet. //set options on the socket int sndBufSize = 1000L * 1024L; theSocket->Set(osSocket, addr); theSocket->InitNonBlocking(osSocket); theSocket->NoDelay(); theSocket->KeepAlive(); theSocket->SetSocketBufSize(sndBufSize); theSocket->RequestEvent(EV_RE); this->RunNormal(); return theTask; }
TCPSocket TCPServerSocket::accept(){ if(!*this){ throw setka::Exc("TCPServerSocket::Accept(): the socket is not opened"); } this->clearCanReadFlag(); sockaddr_storage sockAddr; #if M_OS == M_OS_WINDOWS int sock_alen = sizeof(sockAddr); #elif M_OS == M_OS_LINUX || M_OS == M_OS_MACOSX || M_OS == M_OS_UNIX socklen_t sock_alen = sizeof(sockAddr); #else # error "Unsupported OS" #endif TCPSocket sock;//allocate a new socket object sock.socket = ::accept( this->socket, reinterpret_cast<sockaddr*>(&sockAddr), &sock_alen ); if(sock.socket == DInvalidSocket()){ return sock;//no connections to be accepted, return invalid socket } #if M_OS == M_OS_WINDOWS sock.createEventForWaitable(); //NOTE: accepted socket is associated with the same event object as the listening socket which accepted it. //Re-associate the socket with its own event object. sock.setWaitingEvents(0); #endif sock.setNonBlockingMode(); if(this->disableNaggle){ sock.disableNaggle(); } return sock;//return a newly created socket }
void HttpInterfaceFactory::HttpInterfaceFactoryThread::run() { const uint32 maxTimeout = MAX_UINT32; int res = 0; set<Selectable*> readReady; set<Selectable*> writeReady; IPnPort address( 0, 0 ); if ( ! m_socket->getSockName( address.first, address.second ) ) { mc2dbg << "[HttpIF]: Failed to get socket name." << endl; } while ( !terminated ) { res = m_selector->select( maxTimeout, readReady, writeReady ); if ( !readReady.empty() && *readReady.begin() == m_socket ) { // Accept all new sockets in queue TCPSocket* newSocket = NULL; do { newSocket = m_socket->accept(); if ( newSocket != NULL ) { // Set non blocking newSocket->setBlocking( false ); uint32 IP = 0; uint16 port = 0; if ( newSocket->getPeerName( IP, port ) ) { mc2dbg2 << "Connection from " << prettyPrintIP( IP ) << " port " << port << endl; m_factory->putNewRequest( new HttpInterfaceRequest( newSocket, address ) ); } else { // No peer, then broken socket mc2log << warn << " Couldn't get peer, aborting request." <<endl; delete newSocket; } } } while ( newSocket != NULL ); readReady.clear(); m_selector->addSelectable( m_socket, true, false ); } } // End while !terminated mc2log << info << "HttpInterfaceFactoryThread ends" << endl; }
TCPSocket* TCPSocket::accept() { TCPSocket *pNewSocket = new TCPSocket; sockaddr_in conAddr; memset(&conAddr, 0, sizeof(conAddr)); int nAddrLen = sizeof(conAddr); SOCKET hConnSocket = ::accept(m_hSocket, (sockaddr*)&conAddr, &nAddrLen); if(INVALID_SOCKET == hConnSocket) { Logger::getInstace()->error("TCPSocket >> accept 返回一个INVALID_SOCKET"); delete pNewSocket; return NULL; } pNewSocket->attach(hConnSocket); pNewSocket->setPeerAddr(conAddr); return pNewSocket; }
TCPSocket* Session::openDataConnection(void) { TCPSocket* sock = NULL; if (m_data_pasv) { sock = m_sock_data->accept(); } else { sock = new TCPSocket; sock->connect(m_data_addr, m_data_port); sock->setKeepAlive(true); } return sock; }
int main(void) { TCPSocket socket; char command[10000]; char result[10000]; socket.setIP("127.0.0.1").setPort(8888) .connect() .getCommand(command) .displayCommand() .executeCommand(result) .displayResponse() .connect() .sendResult(result); return 0; }
int16_t networkReader(void *userdata) { if(userdata == NULL) { return 0; } TCPSocket *tcps = (TCPSocket *)userdata; uint8_t data[1]; ssize_t result = 0; try { result = boost::asio::read(*(tcps->getSocket()), boost::asio::buffer(data, 1)); } catch (std::exception& e) { return -2; } if(result <= 0) { return -1; } else { return (uint16_t)data[0]; } }