Beispiel #1
0
int main ()
{
    logFile = new std::ofstream;
    (*logFile).open("client_tester.log", std::ios_base::app);


    testerAddr.sin_family = AF_INET;
    testerAddr.sin_port = (uint16_t) port;
    socklen_t addressLength = sizeof(sockaddr_in);
    memset(&testerAddr, 0, addressLength);

    // create bind and listen on socket
    createSocket();
    bindSocket();
    listenSocket();

    // get few commands and print them to log file and stdout?
    std::cout << "waiting to accept connection..." << std::endl;
    commandSocketFD = accept(testerSocketFD, reinterpret_cast<struct sockaddr *>(&cliAddr), &addressLength);
    ssize_t readSize = read(commandSocketFD, buff, MAX_BUFFER_LENGTH);
    std::cout << "buff: " << buff << std::endl;

    // send responses

}
Beispiel #2
0
/*
 * initExpprocSocket()
 *
 * Creates the listen socket for communication to Expproc fro other processes
 *
 * instead of signal handler etc, this routine create a thread to handle the accept
 * thus removing the need for socketfuncs.c and asyncIO.c
 *
 *    Author greg Brissey 3/12/2006
 */
int initExpprocSocket()
{
	int	status, ival;
	int	applPort;
        void *AcceptConnection( void *arg);

	pApplSocket = createSocket( SOCK_STREAM );
	if (pApplSocket == NULL)		/* each call to program in */
	  return( -1 );				   /* sockets.c sets errno */
	ival = openSocket( pApplSocket );
	if (ival != 0)
	  return( -1 );
	ival = bindSocketAnyAddr( pApplSocket );
	if (ival != 0)
        {
	  errLogSysRet(ErrLogOp,debugInfo,"initExpprocSocket: bindSocketAnyAddr failed:" );
	  return( -1 );
         }
	applPort = returnSocketPort( pApplSocket );
	ival = listenSocket( pApplSocket );
	if (ival != 0)
        {
	  errLogSysRet(ErrLogOp,debugInfo,"initExpprocSocket: listenSocket failed:" );
	  return( -1 );
         }


 	 savePortInfo( applPort ); 
         pAcceptQueue = rngBlkCreate(128,"AcceptQ", 1);  /* accepted socket queue */

        /* create thread to handle the accept */
        status = pthread_create (&AcceptThreadId, NULL, AcceptConnection, (void*) pApplSocket);
	return( 0 );

}
/******************************************
 * Initialisieren und starten des Servers
 */
void* handleServer(){
  #ifdef _DEBUG
  fprintf(stderr,"++ handleserver\n");
  #endif
  char    bOK         = TRUE;
  int     sProxyClient= ~0,
          sProxyWait  = ~0;
  struct  sockaddr_in saAddress;
  struct  threadParam *pThreadParam;

  if(!generateProxyAddress(&saAddress))             return NULL;
  if(!createSocket        (&sProxyWait))            return NULL;
  if(!bindSocket          (&sProxyWait,&saAddress)) return NULL;
  if(!listenSocket        (&sProxyWait))            return NULL;

  //Endlos-schleife fuer accepts
  while(1){
    bOK=acceptSocket(sProxyWait,&sProxyClient);
    if(bOK==TRUE){
      #ifdef _DEBUG
      fprintf(stderr,"***threadNewClient %d\n",sProxyClient);
      #endif
      pThreadParam=(struct threadParam*)malloc(sizeof(struct threadParam));
      pThreadParam->socketID=sProxyClient;
      threadNewClient((void*)pThreadParam);
    }
  }
  closesocket(sProxyWait);

  #ifdef _DEBUG
  fprintf(stderr,"-- handleserver\n");
  #endif
}
Beispiel #4
0
int main(int argc, char **argv)
{
    {
        Database db(DBFILENAME);
        db.init();
    }
   
    printf("MAXNSLICE: %lu\n", MAXNSLICE);
    struct sockaddr_in  cliaddr;
    socklen_t len = sizeof(cliaddr);
    char buff[MAXLINE];
    int listenfd, srvConnfd;

    Socket listenSocket(SRV_SOCKET, NULL, CTRPORT);
    listenfd = listenSocket.init();

    std::cout << "Listen socket port: " << CTRPORT << std::endl;

    pthread_t tid;
    

    while (1)
    {  
        srvConnfd = listenSocket.tcpAccept(listenfd, (SA *) &cliaddr, &len);
        printf("connection from %s, port %d\n",
                inet_ntop(AF_INET, &cliaddr.sin_addr.s_addr, buff, sizeof(buff)), ntohs(cliaddr.sin_port));
        ThreadArg * pthreadArg = new ThreadArg;
        pthreadArg->fd = srvConnfd;
        Pthread_create(&tid, NULL, &clientConnect, pthreadArg);
    }
    return 0;   
}
main() {
  
	printf("%d: Avvio del server...\n", getpid());
	
	createSocketStream(&listensdDiServizio);

	inizializza_memset(&servaddrDiServizio, SERVICE_PORT);
	
	bindSocket(&listensdDiServizio, &servaddrDiServizio);
	
	listenSocket(&listensdDiServizio, BACKLOG);
	
	int i;
	lista_server = malloc(NUMERODISERVERREPLICA*30*sizeof(char));
	for(i = 0; i < NUMERODISERVERREPLICA; i++) 
		lista_server[i] = malloc(30*sizeof(char));
	
	prendi_indirizzi(lista_server);    //prelievo e memorizzazione indirizzi da file LISTA_SERVER

	//printf("prova funzioni ok %s", lista_server[4]);
	
	//--------------------------------------------------------




	pid = fork();  //creo un server figlio
	
	acceptClientDNS();  //che accetta richieste DNS
	

	if(pid > 0) {  //il padre è >0 (se è 0 è il figlio)

		(void) signal(SIGINT, interrompi); //Gestisce l'interruzione con ctrl-c
		
			
		printf("%d: Server avviato\n", getpid());
		
		// -1 sta per aspetto qualasiasi figlio che termina, 0 sta per nessuna opzione, rimango bloccato fino a che non muore qualche figlio.
		waitpid(-1, &pid, 0);
		
		printf("%d: Il server è stato arrestato per qualche errore!\n", getpid());
		exit(0);
	}

}   //-------------------------end main----------------
Beispiel #6
0
/**
 * Creates a socket to listen on and binds it to the local port.
 */
void TNonblockingServer::createAndListenOnSocket() {
  THRIFT_SOCKET s;

  struct addrinfo hints, *res, *res0;
  int error;

  char port[sizeof("65536") + 1];
  memset(&hints, 0, sizeof(hints));
  hints.ai_family = PF_UNSPEC;
  hints.ai_socktype = SOCK_STREAM;
  hints.ai_flags = AI_PASSIVE | AI_ADDRCONFIG;
  sprintf(port, "%d", port_);

  // Wildcard address
  error = getaddrinfo(NULL, port, &hints, &res0);
  if (error) {
    throw TException("TNonblockingServer::serve() getaddrinfo " +
                     string(THRIFT_GAI_STRERROR(error)));
  }

  // Pick the ipv6 address first since ipv4 addresses can be mapped
  // into ipv6 space.
  for (res = res0; res; res = res->ai_next) {
    if (res->ai_family == AF_INET6 || res->ai_next == NULL)
      break;
  }

  // Create the server socket
  s = socket(res->ai_family, res->ai_socktype, res->ai_protocol);
  if (s == -1) {
    freeaddrinfo(res0);
    throw TException("TNonblockingServer::serve() socket() -1");
  }

  #ifdef IPV6_V6ONLY
  if (res->ai_family == AF_INET6) {
    int zero = 0;
    if (-1 == setsockopt(s, IPPROTO_IPV6, IPV6_V6ONLY, const_cast_sockopt(&zero), sizeof(zero))) {
      GlobalOutput("TServerSocket::listen() IPV6_V6ONLY");
    }
  }
  #endif // #ifdef IPV6_V6ONLY


  int one = 1;

  // Set THRIFT_NO_SOCKET_CACHING to avoid 2MSL delay on server restart
  setsockopt(s, SOL_SOCKET, THRIFT_NO_SOCKET_CACHING, const_cast_sockopt(&one), sizeof(one));

  if (::bind(s, res->ai_addr, static_cast<int>(res->ai_addrlen)) == -1) {
    ::THRIFT_CLOSESOCKET(s);
    freeaddrinfo(res0);
    throw TTransportException(TTransportException::NOT_OPEN,
                              "TNonblockingServer::serve() bind",
                              THRIFT_GET_SOCKET_ERROR);
  }

  // Done with the addr info
  freeaddrinfo(res0);

  // Set up this file descriptor for listening
  listenSocket(s);
}
Beispiel #7
0
bool
CProxy::start(const std::string&                  sListenIP,
              ushort                              uListenPort,
              const std::string&                  sLoginSrvIP,
              ushort                              uLoginSrvPort,
              const std::vector<s_serverInfos>&   vecAreas,
              ushort                              uMaxConnections)
{
  // Check if listen address is correctly formated
  if (!m_listenAddress.FromStringExplicitPort(sListenIP.c_str(), uListenPort))
  {
    log_ERROR("Invalid listen address. Aborting.");
    return false;
  }


  // Start listen interface
  RakNet::SocketDescriptor listenSocket(uListenPort, sListenIP.c_str());
  m_pListenInterface = RakNet::RakPeerInterface::GetInstance();

  if (m_pListenInterface->Startup(uMaxConnections, &listenSocket, 1) != RakNet::RAKNET_STARTED)
  {
    log_ERROR("Failed to startup Raknet interface. Aborting.");
    stop();
    return false;
  }

  m_pListenInterface->SetMaximumIncomingConnections(uMaxConnections);
  ff::write(pan::notice, "Started listening on ", sListenIP, ":", uListenPort, ".");
  ff::write(pan::notice, "Accepting max ", uMaxConnections, " connections.");

  ushort uTmpPort = 49777;

  // Start login server interface
  {
    // Check if login server address is correctly formated
    if (!m_loginSrvAddress.FromStringExplicitPort(sLoginSrvIP.c_str(), uLoginSrvPort))
    {
      log_ERROR("Invalid login server address. Aborting.");
      stop();
      return false;
    }

    RakNet::SocketDescriptor loginSocketDesc(++uTmpPort, NULL);

	  while (RakNet::SocketLayer::IsPortInUse(loginSocketDesc.port, loginSocketDesc.hostAddress, loginSocketDesc.socketFamily))
      loginSocketDesc.port = uTmpPort++;
      
    // Create and startup login server interface
    m_pLoginSrvInterface = RakNet::RakPeerInterface::GetInstance();

	  if (m_pLoginSrvInterface->Startup(1, &loginSocketDesc, 1) != RakNet::RAKNET_STARTED)
    {
      log_ERROR("Failed to startup login server interface.");
      stop();
      return false;
    }

    int latency = ping(m_pLoginSrvInterface, sLoginSrvIP, uLoginSrvPort);
    
    if (latency < 0)
      ff::write(pan::warning, "Failed to ping login server (", sLoginSrvIP, ":", uLoginSrvPort, ").");
    else
      ff::write(pan::notice, "Pinged login server (", sLoginSrvIP, ":", uLoginSrvPort, ") - ", latency, "ms.");

    // Attempt connection
    if (m_pLoginSrvInterface->Connect(sLoginSrvIP.c_str(), uLoginSrvPort, NULL, 0) != RakNet::CONNECTION_ATTEMPT_STARTED)
    {
      ff::write(pan::error, "Connection to login server (", sLoginSrvIP, ":", uLoginSrvPort, ") failed.");
      stop();
      return false;
    }

    m_pLoginSrvInterface->SetOccasionalPing(true);
  }

  // Connect to area servers
  for (std::vector<s_serverInfos>::const_iterator it = vecAreas.begin();
       it != vecAreas.end();
       it++)
  {
    RakNet::SocketDescriptor areaSocketDesc(uTmpPort++, NULL);

	  while (RakNet::SocketLayer::IsPortInUse(areaSocketDesc.port, areaSocketDesc.hostAddress, areaSocketDesc.socketFamily))
      areaSocketDesc.port = uTmpPort++;

    RakNet::RakPeerInterface* pAreaItf = RakNet::RakPeerInterface::GetInstance();

	  if (pAreaItf->Startup(1, &areaSocketDesc, 1) != RakNet::RAKNET_STARTED)
    {
      log_ERROR("Failed to startup an area server interface.");
      continue;
    }

    if (pAreaItf->Connect((*it).m_srvIP.c_str(), (*it).m_srvPort, NULL, 0) != RakNet::CONNECTION_ATTEMPT_STARTED)
    {
      ff::write(pan::error, "Connection attempt to area server (", (*it).m_srvIP, ":", (*it).m_srvPort, ") failed.");
      continue;
    }

    pAreaItf->SetOccasionalPing(true);

    // TODO: Do something here with this connection
  }


  // Proxy server started successfuly
  m_pListenInterface->AttachPlugin(this);
  m_bStarted = true;

  m_bQuit = false;
  m_pUpdateThread = new boost::thread(FastDelegate0<>(this, &CProxy::updateThread));

  return m_bStarted;
}
Beispiel #8
0
// MAIN
int main(int argc, char **argv) {
   // Local variables
   int pid;
   int port;
   int listenfd;
   int connfd;
   struct sockaddr_in clientAddr;
   socklen_t clientSize = sizeof(clientAddr);
   FILE* logFile;

   // gets port number
   if(argc == 2) {
      port = atoi(argv[1]);
   } else {
      perror("Invalid arguments.");
      exit(1);
   }

   // opens log file
   logFile = fopen("log.txt", "a+");

   // creates listen socket
   listenfd = listenSocket(port);

   // starts listening
   Listen(listenfd, LISTENQUEUE); 

   for ( ; ; ) {
      // accepts a connection
      connfd = Accept(listenfd, (struct sockaddr *)&clientAddr, &clientSize);

      // prints the info
      PrintConnectionInfo(clientAddr);

      // log
      logConnection(logFile, clientAddr);

      // fork
      if((pid = fork()) == 0) {
         // child process closes the listen socket
         close(listenfd);
         
         // process
         process(connfd, clientAddr);
         
         // child process closes the connection
         close(connfd); 

         // prints info of disconnection
         printDisconnectInfo(clientAddr);

         // log
         logDisconnection(logFile, clientAddr);

         // finished execution
         exit(0); 
      }

      // parent process closes the connection with client
      close(connfd);
   }

   // closes log file
   fclose(logFile);

   return(0);
}
Beispiel #9
0
	//开始
	void start()
	{
		sock_ptr listenSocket(new ip::tcp::socket(ios));
		////异步监听
		acc.async_accept(*listenSocket, boost::bind(&server::accept_handler, this, boost::asio::placeholders::error, listenSocket));
	}
Beispiel #10
0
int chunkserver_init(int argc, char *argv[])
{

	/* Set path of chunkserver */
	chunk_path = (char*)malloc(sizeof(char)*(strlen(argv[1])+1));	
	if(chunk_path == NULL){
		printf("%s: Failed to allocate memory\n",__func__);
		return -1;	
	}	
	strcpy(chunk_path,argv[1]);
	#ifdef DEBUG
		printf("path is %s\n", chunk_path);
	#endif
	char command[50];
	sprintf(command, "rm -fr %s", chunk_path);
	system(command);
	mkdir(chunk_path, 0777);	
	/* Set ip addr and port of master */
	strcpy(master.ip_addr, argv[2]);
	master.port = MASTER_LISTEN;
	#ifdef DEBUG
		printf("Master ip address = %s port = %d\n", master.ip_addr, master.port);
	#endif

	/* Set heartbeat port of chunkserver */
	heartbeat_port = atoi(argv[3]);	
	#ifdef DEBUG
		printf("Chunkserver heartbeat port is %d\n", heartbeat_port);
	#endif

	/* Set ip addr of chunkserver */
//	strcpy(chunkserver.ip_addr, argv[4]);
	getSelfIp(&chunkserver);
	#ifdef DEBUG
		printf("Chunkserver ip address = %s\n", chunkserver.ip_addr);
	#endif

	/* Set client port of chunkserver */
	chunkserver.port = atoi(argv[4]);	
	#ifdef DEBUG
		printf("Chunkserver client port is %d\n", chunkserver.port);
	#endif

	if((client_listen_socket = createSocket())==-1){
		printf("%s: Failed to create socket\n",__func__);
		return -1;	
	}
        if((bindSocket(client_listen_socket, chunkserver.port, chunkserver.ip_addr))==-1){
		printf("%s: Failed bind to the port\n",__func__);
		return -1;	
	}
        if((listenSocket(client_listen_socket))==-1){
		printf("%s: Could not start the listener\n",__func__);
		return -1;	
	}

	if((master_socket = createSocket())==-1){
                printf("%s: Failed to create socket\n",__func__);
                return -1;
        }
        if((bindSocket(master_socket, heartbeat_port, chunkserver.ip_addr))==-1){
		printf("%s: Failed bind to the port\n",__func__);
		return -1;	
	}
	if(createConnection(master,master_socket)==-1){
		printf("%s: Could not connect to the master\n",__func__);
		return -1;
	}

	pthread_mutex_init(&seq_mutex, NULL);
	//recv an ack
	//send IP and Port details
		
	return 0;
}