示例#1
0
int main(int argc, char ** argv) {

  int PORT;
  if(argc>1) {
    PORT = atoi(argv[1]);
  } else {
    PORT = 5555;
  }

  int sock = init_socket();
  if(sock == -1) {
    printf("Erreur socket\n");
    return -1;
  } else {
    char * hostname = "127.0.0.1";
    struct sockaddr_in sin = init_sockaddr(hostname, PORT);

    int connexion = connect(sock, (struct sockaddr *)&sin, sizeof(sin));
    if(connexion == -1) {
      printf("Erreur connect()\n");
      return -1;
    } else {

      pthread_t thread;
      pthread_create(&thread, NULL, boucle_recv, (void*)&sock);
      pthread_detach(thread);

      FILE * flux_write = fdopen(sock, "w");
      while(1) {
	char buf[4];
	printf("> ");
	scanf("%s", buf);
        envoyer(buf, sock, flux_write);
      }
    }


  }
    return 0;
}
示例#2
0
文件: server.c 项目: hex636b/tftp
int main(int argc, char ** argv )
{
	int ret;
	int sockfd;

	pid_t pid;
	tftp_t req = {0};	

	struct sockaddr_in peer = {0}; //客户端地址
	int addrlen = sizeof(peer);
	

	init_server();

	sockfd = init_socket();
	if( sockfd < 0 )
		return -1;

	while(1)
	{
		//读取客户请求
		addrlen = sizeof(peer);
		ret = recvfrom(sockfd,&req,sizeof(req),0,(SAP)&peer, &addrlen);
		if( ret <= 0 )
			continue;

		pid = fork();
		if( 0==pid)
		{
			close(sockfd);
			service(&req, &peer); //交子进程处理
			return 0;
		}
	}	

	close(sockfd);
	return 0;

} //end of main()
示例#3
0
int main()
{
    signal(SIGINT, signal_handler);

    stage current_stage = FIRST_STAGE;

    int serverfd = init_socket();
    int clientfd = -1;

    printf("header size %d\n", hdr_sz);

    while (!stop) { //this will be removed in the GTK swupdate GUI
        usleep(100000); //this will be removed in the GTK swupdate GUI
        switch (current_stage) {
            case FIRST_STAGE:
            {
                clientfd = accept_client(serverfd);
                if (clientfd == -1) {
                    continue;
                }
                current_stage = SECOND_STAGE;
                break;
            }
            case SECOND_STAGE:
            {
                read_messages(clientfd);
                close(clientfd);
                current_stage = FIRST_STAGE; //loop-back
                break;
            }
        }
    }

    printf("Done...\n");
    close(serverfd);
    unlink(socket_path);

    return 0;
}
示例#4
0
文件: tcp.c 项目: longqzh/daegu-DCU
int connectToAMI()
{
	init_socket();

	// connect with blocking
	
	if( connect(sock_fd,(struct sockaddr *)&addr_serv,sizeof(struct sockaddr)) < 0){
		close(sock_fd);
		sprintf(tmpdebug,"\tConnect to Server fail:(%d)%s",errno,strerror(errno));
		mylog(tmpdebug,CURRENT_COM);
		return -3;
	} else {
		mylog("\tConnect to Server sucessful!",CURRENT_COM);
		connection_state=1;
	}
	

	// Get client IP Address

	strncpy(ifr.ifr_name, ETH_NAME, IFNAMSIZ);
	ifr.ifr_name[IFNAMSIZ - 1] = 0;

	if (ioctl(sock_fd, SIOCGIFADDR, &ifr) < 0){
		perror("ioctl");
		return -4;
	}

	memcpy(&sinc, &ifr.ifr_addr, sizeof(sinc));
	fprintf(stdout, "eth0: %s\n", inet_ntoa(sinc.sin_addr));

	strcpy(myIPBuf,inet_ntoa(sinc.sin_addr));

	// init tcpseq

	tcpseq=0x04;
	
	return 1;

}
示例#5
0
int main(int argc, char *argv[])
{
	if (argc != 3 || strcmp(argv[1], "-i") != 0) {
		print_usage();
		exit(EXIT_SUCCESS);
	}

	int fd;
	
	if ((fd = init_socket(argv[2], protocol_ip, false)) < 0) {
		exit(EXIT_FAILURE);
	}

	int i;
	for (i = 0; i < 30; ++i) {
		printf("No.%04d ", i+1);
		capture_socket_once(fd, proto_parse);
	}

	drop_socket(fd, argv[2]);

	return EXIT_SUCCESS;
}
int main(int argc, char *argv[])
{
  char *txt;
  int desc, remaining, bytes_written, len, s, port, child;

  if (argc != 3 || (port = atoi(argv[1])) < 1024) {
    fprintf(stderr, "usage: %s <portnum> <\"-\" | filename>\n", argv[0]);
    exit(1);
  }
  s = init_socket(port);
  len = strlen(txt = get_text(argv[2]));

  if ((child = fork()) > 0) {
    fprintf(stderr, "Sign started on port %d (pid %d).\n", port, child);
    exit(0);
  }
  signal(SIGCHLD, reap);

  for (;;) {
    if ((desc = accept(s, (struct sockaddr *) NULL, 0)) < 0)
      continue;

    if (fork() == 0) {
      remaining = len;
      do {
	if ((bytes_written = write(desc, txt, remaining)) < 0)
	  exit(0);
	else {
	  txt += bytes_written;
	  remaining -= bytes_written;
	}
      } while (remaining > 0);
      exit(0);
    }
    close(desc);
  }
}
示例#7
0
static void spondoolies_detect_sp30(__maybe_unused bool hotplug)
{
	struct cgpu_info *cgpu = calloc(1, sizeof(*cgpu));
	struct device_drv *drv = &sp30_drv;
	struct spond_adapter *a;

#if NEED_FIX
	nDevs = 1;
#endif

	assert(cgpu);
	cgpu->drv = drv;
	cgpu->deven = DEV_ENABLED;
	cgpu->threads = 1;
	cgpu->device_data = calloc(sizeof(struct spond_adapter), 1);
	if (unlikely(!(cgpu->device_data)))
		quit(1, "Failed to calloc cgpu_info data");
	a = cgpu->device_data;
	a->cgpu = (void *)cgpu;
	a->adapter_state = ADAPTER_STATE_OPERATIONAL;
	a->mp_next_req = allocate_minergate_packet_req_sp30(0xca, 0xfe);
	a->mp_last_rsp = allocate_minergate_packet_rsp_sp30(0xca, 0xfe);

	pthread_mutex_init(&a->lock, NULL);
	a->socket_fd = init_socket();
	if (a->socket_fd < 1) {
		applog(LOG_ERR, "SP30: Failed to connect to minergate server");
		_quit(-1);
	}

	assert(add_cgpu(cgpu));
	// Clean MG socket
	spondoolies_flush_queue(a, true);
	spondoolies_flush_queue(a, true);
	spondoolies_flush_queue(a, true);
	applog(LOG_DEBUG, "SP30: SPOND spondoolies_detect_sp30 done");
}
示例#8
0
SOCKET socket_create(int port)
{
	if(init_socket()==-1)
		return 0;
	SOCKET st=socket(AF_INET,SOCK_STREAM,0);
	if(st==0)
	{
		return 0;
	}
#ifdef WIN
	const char on=0;
#else
	int on=0;
#endif
	if(setsockopt(st,SOL_SOCKET,SO_REUSEADDR,&on,sizeof(on))==-1)
	{
		printf("setsockopt failed %s\n",strerror(errno) );
		return EXIT_FAILURE;
	}
	struct sockaddr_in addr;//定义一个ip的结构
	memset(&addr,0,sizeof(addr));
	addr.sin_family=AF_INET;//设置结构类型为Tcp/ip
	addr.sin_port=htons(port);//设置端口号htons:将short类型从本地字节类型转化为net字节类型
	addr.sin_addr.s_addr=htonl(INADDR_ANY);//转化为网络类型
	if(bind(st,(struct sockaddr *)&addr,sizeof(addr))==-1)
	{
		printf("bind error %s\n",strerror(errno));
		return EXIT_FAILURE;
	}
	if(listen(st,20)==-1){//同时有多少连接过来
		printf("listen error %s\n",strerror(errno));
		return EXIT_FAILURE;
	}	
	printf("listen %d success\n",port );
	return st;
}
示例#9
0
文件: windows.c 项目: GYGit/Soar
int init_input(int argc, char *argv[]) {
	int i;
	
	for (i = 1; i < argc; ++i) {
		if (strcmp(argv[i], "-s") == 0) {
			if (i + 1 >= argc) {
				fprintf(stderr, "specify a socket path or port\n");
				return 0;
			}
			input_type = SOCKET_INPUT;
			return init_socket(argv[i + 1]);
		} else if (strcmp(argv[i], "-f") == 0) {
			if (i + 1 >= argc) {
				fprintf(stderr, "specify file path\n");
				return 0;
			}
			input_type = FILE_INPUT;
			return init_file(argv[i + 1]);
		}
	}
	file = stdin;
	input_type = FILE_INPUT;
	return 1;
}
示例#10
0
文件: std.c 项目: cyrillos/compel
int __export_std_compel_start(struct prologue_init_args *args,
			      const plugin_init_t * const *init_array,
			      size_t init_size)
{
	unsigned int i;
	int ret = 0;

	init_args = args;

	ret = init_socket(args);
	if (ret)
		return ret;

	for (i = 0; i < plugin_init_count(init_size); i++) {
		const plugin_init_t *d = init_array[i];

		if (d && d->init) {
			ret = d->init();
			if (ret)
				break;
		}
	}

	if (!ret)
		ret = main(args->arg_p, args->arg_s);

	for (; i > 0; i--) {
		const plugin_init_t *d = init_array[i - 1];

		if (d && d->exit)
			d->exit();
	}

	fini_socket();
	return ret;
}
示例#11
0
void main(int argc, char **argv)
{
   bool	 running = TRUE;

   /*---------------------------------------------------*/
   /* parse command line arguments and initialize stuff */
   /*---------------------------------------------------*/

   parse_args( argc, argv );
   log_file.init_log(TRUE,TRUE,2,NULL);
   read_config_file();

   init_socket();

   command.list_commands();
   command.prompt();
   do
   {
      command.get_input();
      switch( command.input[0] )
      {

         case 'd':
         	server_list.ListServers();
         	break;

         case 'b':
         	banned_list.ListServers();
         	break;

         case 'r':
			   read_config_file();
         	break;

         case 'g':
         	query_game();
//            wait_for_response( GAMESVR_REPLY );
            break;

      	case 'q':
         case 'Q':
         	running = FALSE;
            break;

         case 'l':
         	enable_log = !enable_log;
            log_file.set_log(enable_log);
            cout << "Log file is " << (enable_log?"on.":"off.") << endl;
         	break;

         case 'e':
         	enable_echo = !enable_echo;
            log_file.set_echo(enable_echo);
            cout << "Log echo is " << (enable_echo?"on.":"off.") << endl;
         	break;

         case '?':
         case 'h':
         	command.list_commands();
            break;

         default:
         case 'x':
         	server_list.DeleteList();
         	break;
      }
      if( GetTickCount() > next_reload_time )
      {
      	read_config_file();
         next_reload_time = GetTickCount() + reload_interval;
      }
      command.prompt();
   }
   while( running );
}
示例#12
0
int main(int argc, char* argv[])
{
	int packet_length;
	uint16_t msg_id, msg_id_rcv;
	mqtt_broker_handle_t broker;

   mqtt_init(&broker, "sancho");
   mqtt_init_auth(&broker, "quijote", "rocinante");
   init_socket(&broker, "192.168.10.40", 1883, keepalive);

	// >>>>> CONNECT
	mqtt_connect(&broker);
	// <<<<< CONNACK
	packet_length = read_packet(1);
	if(packet_length < 0)
	{
		fprintf(stderr, "Error(%d) on read packet!\n", packet_length);
		return -1;
	}

	if(MQTTParseMessageType(packet_buffer) != MQTT_MSG_CONNACK)
	{
		fprintf(stderr, "CONNACK expected!\n");
		return -2;
	}

	if(packet_buffer[3] != 0x00)
	{
		fprintf(stderr, "CONNACK failed!\n");
		return -2;
	}


	// >>>>> PUBLISH QoS 0
	printf("Publish: QoS 0\n");
	mqtt_publish(&broker, "public/myexample/example", "Test libemqtt message.", 0);
	// >>>>> PUBLISH QoS 1
	printf("Publish: QoS 1\n");
	mqtt_publish_with_qos(&broker, "hello/emqtt", "Example: QoS 1", 0, 1, &msg_id);
	// <<<<< PUBACK
	packet_length = read_packet(1);
	if(packet_length < 0)
	{
		fprintf(stderr, "Error(%d) on read packet!\n", packet_length);
		return -1;
	}

	if(MQTTParseMessageType(packet_buffer) != MQTT_MSG_PUBACK)
	{
		fprintf(stderr, "PUBACK expected!\n");
		return -2;
	}

	MQTTParseMessageId(packet_buffer, msg_id_rcv);
	if(msg_id != msg_id_rcv)
	{
		fprintf(stderr, "%d message id was expected, but %d message id was found!\n", msg_id, msg_id_rcv);
		return -3;
	}

	// >>>>> PUBLISH QoS 2
	printf("Publish: QoS 2\n");
	mqtt_publish_with_qos(&broker, "hello/emqtt", "Example: QoS 2", 1, 2, &msg_id); // Retain
	// <<<<< PUBREC
	packet_length = read_packet(1);
	if(packet_length < 0)
	{
		fprintf(stderr, "Error(%d) on read packet!\n", packet_length);
		return -1;
	}

	if(MQTTParseMessageType(packet_buffer) != MQTT_MSG_PUBREC)
	{
		fprintf(stderr, "PUBREC expected!\n");
		return -2;
	}

	MQTTParseMessageId(packet_buffer, msg_id_rcv);
	if(msg_id != msg_id_rcv)
	{
		fprintf(stderr, "%d message id was expected, but %d message id was found!\n", msg_id, msg_id_rcv);
		return -3;
	}

	// >>>>> PUBREL
	mqtt_pubrel(&broker, msg_id);
	// <<<<< PUBCOMP
	packet_length = read_packet(1);
	if(packet_length < 0)
	{
		fprintf(stderr, "Error(%d) on read packet!\n", packet_length);
		return -1;
	}

	if(MQTTParseMessageType(packet_buffer) != MQTT_MSG_PUBCOMP)
	{
		fprintf(stderr, "PUBCOMP expected!\n");
		return -2;
	}

	MQTTParseMessageId(packet_buffer, msg_id_rcv);
	if(msg_id != msg_id_rcv)
	{
		fprintf(stderr, "%d message id was expected, but %d message id was found!\n", msg_id, msg_id_rcv);
		return -3;
	}

	// >>>>> DISCONNECT
	mqtt_disconnect(&broker);
	close_socket(&broker);
	return 0;
}
示例#13
0
文件: main.c 项目: borlak/acmud
// game boot up stuff
void init_mud(long hotreboot)
{
	char buf[MAX_BUFFER];
	MSOCKET *socket;
	extern CREATURE *hash_creature[HASH_KEY];
	extern OBJECT *hash_object[HASH_KEY];
	extern ROOM *hash_room[HASH_KEY];
	extern char **connect_attempts;
	extern void backup_update();
#ifndef WIN32
	struct itimerval itime;
	struct timeval time;
#endif
	extern char * const months[];
	extern char * const days[];
	long x;

	for(x = 0; months[x]; x++) ;
	mudtime.months = x;
	for(x = 0; days[x]; x++) ;
	mudtime.days = x;

	// init hash tables
	memset(hash_creature,	0,sizeof(hash_creature));
	memset(hash_object,	0,sizeof(hash_object));
	memset(hash_room,	0,sizeof(hash_room));
	memset(hash_reset,	0,sizeof(hash_reset));

	// set up process signals to catch and deal with
	signal(SIGINT,		signal_handler);
	signal(SIGILL,		signal_handler);
	signal(SIGFPE,		signal_handler);

	signal(SIGSEGV,		signal_handler);
	signal(SIGPIPE,		SIG_IGN);	// ignore pipes! tx to unix socket faq for help
						// with this.  http://http://www.developerweb.net/forum/
#ifndef WIN32
	signal(SIGTRAP,		signal_handler);
	signal(SIGVTALRM,	signal_handler);

	// this code is to check for infinite looping
	time.tv_sec		= 5;
	time.tv_usec		= 0;
	itime.it_interval	= time;
	itime.it_value		= time;
	if( setitimer(ITIMER_VIRTUAL, &itime, 0) < 0 )
		mudlog("Error starting setitimer.");
#endif

	// initialize the random number generator
	init_rand();

	// connect_attempts array, to keep people from spam connecting to slow down the mud
        connect_attempts        = malloc(sizeof(char*));
        connect_attempts[0]     = 0;

	mysql = mysql_init(NULL);       
       if (!mysql)
       {
               mudlog("Error initializing MySQL: %s", mysql_error(mysql));
               abort();
       }

        // connect to MySQL database
       if (!mysql_real_connect(mysql, DB_HOST, DB_LOGIN, DB_PASSWORD, DB_NAME, 0, NULL, 0))
        {
               mudlog("Error opening mysql database: %s", mysql_error(mysql));
                abort();
        }

        if (mysql_select_db(mysql, DB_NAME))
        {
               mudlog("Error opening main database: %s",mysql_error(mysql));
               if (mysql)
                       mysql_close(mysql);
                abort();
        }

	// time of da mud !
	fread_time();

	// load areas/rooms/objects/creatures
	load_db();

	// check if hotreboot and reconnect everything
	if(hotreboot)
	{
		MSOCKET *socket=0;
		char buf[MAX_BUFFER];
		MYSQL_RES *result;
		MYSQL_ROW row;

		mysql_query(mysql, "SELECT * FROM player WHERE online='1'");
		result = mysql_store_result(mysql);

		if (mysql_num_rows(result) < 0)
		{
			mudlog("hotreboot: mysql error is: %s",mysql_error(mysql));
			exit(1);
		}

		while((row = mysql_fetch_row(result)))
		{
			strcpy(buf, row[P_NAME]);

			// check for "host" player.. holds control descriptor
			if(!strcasecmp("host", row[C_NAME]))
			{
				host = atoi(row[P_DESCRIPTOR]);
			}
			else
			{
				socket = init_socket();
				fread_player(socket, buf);

				str_dup(&socket->host,		row[P_HOST]);
				str_dup(&socket->ip,		row[P_IP]);

				socket->desc = atoi(row[P_DESCRIPTOR]);
				socket->connected = CON_PLAYING;

				trans(socket->pc, socket->pc->in_room);

				sendcrit(socket->pc, "Hotreboot completed.");
			}
		}
		mysql_free_result(result);
	}

	// make sure nobody has non-existant connections, in the event of a crash + hotreboot
	// then go through and update people who are online
	// this is also a good time to get host address, as players will be expecting lag
	mysql_query(mysql, "UPDATE player SET online='0', descriptor='0'");

	for(socket = socket_list; socket; socket = socket->next)
	{
		get_hostname(socket);
		sprintf(buf,"UPDATE player SET online='1', host=\"%s\" WHERE id='%li'",
			smash_quotes(socket->host), socket->id);
		mysql_query(mysql, buf);
	}

	// see how many players are in each area, to see if area should be 'alive'
	for(socket = socket_list; socket; socket = socket->next)
	{
		if(IsPlaying(socket->pc))
			socket->pc->in_room->area->players++;
	}

	// check if we need to backup
	backup_update();
}
示例#14
0
int appe_tcp_server_init(AppeSocket *sock, const char *local_ip, int local_port, const char *name)
{
    int rtn = -1;
    int val = 1;
    struct sockaddr_in localaddr;
    struct linger linger = { 0 };

    init_socket(sock, name);

    int fd = socket(AF_INET, SOCK_STREAM, 0);
    if (fd == -1) {
        perror("init_tcp_server: init error");
        goto ERROR;
    }

    DEBUG("init %s: local_ip = %s, local_port = %d\n", sock->local_name ,local_ip, local_port);

    memset(&localaddr, 0, sizeof(localaddr));
    localaddr.sin_family = AF_INET;
    localaddr.sin_port = htons(local_port);
    /* localaddr.sin_addr.s_addr = inet_addr(local_ip); */
    if ((NULL == local_ip) || (strcmp(local_ip, "") == 0)) {
        localaddr.sin_addr.s_addr = htonl(INADDR_ANY);
    } else {
        inet_aton(local_ip, &(localaddr.sin_addr));
    }
    memset(&(localaddr.sin_zero), 0, sizeof(localaddr.sin_zero));

    rtn = setsockopt(fd, SOL_SOCKET, SO_REUSEADDR,
                     (const void*)&val, sizeof(val));
    if (rtn < 0) {
        perror("init_tcp_server: setsockopt SO_REUSEADDR error");
        goto ERROR;
    }

    linger.l_onoff = 1;
    linger.l_linger = 3;
    rtn = setsockopt(fd, SOL_SOCKET, SO_LINGER,
                     (const void*) &linger, sizeof(linger));
    if (rtn < 0) {
        perror("init_tcp_server: setsockopt SO_LINGER error");
        goto ERROR;
    }

    /* int buf_size = 1024 * 1024;
     * rtn = setsockopt(fd, SOL_SOCKET, SO_RCVBUF, (const void*)&buf_size, sizeof(int));
     * if (rtn < 0) {
     *     perror("init_tcp_server: setsockopt SO_RCVBUF error");
     *     goto ERROR;
     * }  */

    rtn = bind(fd, (struct sockaddr*)&localaddr, sizeof(localaddr));
    if (rtn == -1) {
        fprintf(stderr, "init %s: bind error, ip = %s, port = %d\n",
                sock->local_name, local_ip, local_port);
        goto ERROR;
    }

    rtn = listen(fd, CONNECT_MAX_REMOTE_NUM);
    if (rtn < 0) {
        perror("init_tcp_server: listen error");
        goto ERROR;
    }

    sock->local_fd = fd;

    // now set NULL to init handler.
    sock->pHandlers = (AppeEventHandler**) malloc(CONNECT_MAX_HANDLER_NUM * sizeof(AppeEventHandler*));
    memset(sock->pHandlers, 0, CONNECT_MAX_HANDLER_NUM * sizeof(AppeEventHandler*));

    return rtn;

ERROR:
    DEBUG("%s server init: goto error\n", sock->local_name);
    free_socket(sock);

    return -1;
}
int HandleNetConn()
{
   int iResult;
   DWORD i;
   DWORD Total;
   ULONG NonBlock;
   DWORD Flags, SendBytes, RecvBytes;
   
	iResult=init_socket();
 
 	if (!iResult)
	{
			// Prepare a socket to listen for connections
		   if (bind(ListenSocket, (PSOCKADDR) &ServerAddr, sizeof(ServerAddr)) == SOCKET_ERROR)
			{
			  printf("error in binding the port");
			  closesocket(ListenSocket);
			  WSACleanup();
			  return ERR_SERVER_BIND_FAILED;
		   }

			printf("Bind succeeded");		 

			if (listen(ListenSocket, MAX))
			{
				printf("error in Listening");
				closesocket(ListenSocket);
				WSACleanup();
				return ERR_SERVER_LISTEN_FAILED;
			}	
			
			printf("\n\nServer Listening\n");

		   // Change the socket mode on the listening socket from blocking to

		   // non-block so the application will not block waiting for requests

		   NonBlock = 1;

		   if (ioctlsocket(ListenSocket, FIONBIO, &NonBlock) == SOCKET_ERROR)
		   {
			  printf("ioctlsocket() failed with error\n");
			  return ERR_IOCTLSOCKET_FAILED;

		   }
	 

		   while(TRUE)
		   {
				// Prepare the Read and Write socket sets for network I/O notification
				FD_ZERO(&ReadSet);
				FD_ZERO(&WriteSet);
				// Always look for connection attempts
				FD_SET(ListenSocket, &ReadSet);

				// Set Read and Write notification for each socket based on the

				// current state the buffer.  If there is data remaining in the

				// buffer then set the Write set otherwise the Read set

				for (i = 0; i < TotalSockets; i++)
				{
						FD_SET(SocketArray[i]->Socket, &ReadSet);
				}

			  if ((Total = select(0, &ReadSet, &WriteSet, NULL, NULL)) == SOCKET_ERROR)
			  {
				 printf("select() returned with error\n");
				 return 1;
			  }
			  else
				printf("select() is OK!\n");

			  // Check for arriving connections on the listening socket.

			  if (FD_ISSET(ListenSocket, &ReadSet))
			  {
				 Total--;
				 if ((AcceptSocket = accept(ListenSocket, NULL, NULL)) != INVALID_SOCKET)
				 {
					// Set the accepted socket to non-blocking mode so the server will
					// not get caught in a blocked condition on WSASends

					NonBlock = 1;
					if (ioctlsocket(AcceptSocket, FIONBIO, &NonBlock) == SOCKET_ERROR)
					{
					   printf("ioctlsocket(FIONBIO) failed with error\n");
					   return 1;
					}
					else
					   printf("ioctlsocket(FIONBIO) is OK!\n");

					if (CreateSocketInformation(AcceptSocket) == FALSE)
					{
						 printf("CreateSocketInformation(AcceptSocket) failed!\n");
						 return 1;
					}
					else
						printf("CreateSocketInformation() is OK!\n");
				 }
				 else
				 {
					if (WSAGetLastError() != WSAEWOULDBLOCK)
					{
					   printf("accept() failed with error\n");
					   return 1;
					}
					else
					   printf("accept() is fine!\n");
				 }
			  }

			  // Check each socket for Read notification until the number
			  // of sockets in Total is satisfied

			  for (i = 0; Total > 0 && i < TotalSockets; i++)
			  {
				 LPSOCKET_INFORMATION SocketInfo = SocketArray[i];

				 // If the ReadSet is marked for this socket then this means data

				 // is available to be read on the socket

				 if (FD_ISSET(SocketInfo->Socket, &ReadSet))

				 {

					Total--;
					SocketInfo->DataBuf.buf = SocketInfo->Buffer;
					SocketInfo->DataBuf.len = DATA_BUFSIZE;
					Flags = 0;

					if (WSARecv(SocketInfo->Socket, &(SocketInfo->DataBuf), 1, &RecvBytes, &Flags, NULL, NULL) == SOCKET_ERROR)
					{
					   if (WSAGetLastError() != WSAEWOULDBLOCK)
					   {
						  printf("WSARecv() failed with error\n");
						  FreeSocketInformation(i);
					   }
					   else
						  printf("WSARecv() is OK!\n");

					   continue;

					}

					else
					{
					   SocketInfo->BytesRECV = RecvBytes;

					   // If zero bytes are received, this indicates the peer closed the connection.

					   if (RecvBytes == 0)
					   {
						  FreeSocketInformation(i);
						  continue;
					   }
					}
				 }
			  }

		   }

		}
		return ERR_SUCCESS;
	}
示例#16
0
int main(int argc, char *argv[])
{
	int socks[2];
	sqlite3 *db;
	sqlite3_stmt *stmt;
	struct sockaddr_can addr;
	long long prev_time = 0;
	long long cur_time = 0;
	struct timeval prev_tv = { 0 };
	struct timeval cur_tv = { 0 };
	long long delay;
	int sock;
	struct isobus_mesg mesg;

	/* Handle options */
	struct arguments arguments = {
		"ib_imp",
		"ib_eng",
		NULL,
		1000000LL,
	};
	if(argp_parse(&argp, argc, argv, 0, 0, &arguments)) {
		perror("argp_parse");
		return EXIT_FAILURE;
	}

	/* Create ISOBUS sockets */
	socks[0] = init_socket(arguments.can_eng);
	socks[1] = init_socket(arguments.can_imp);
	addr.can_family = AF_CAN;
	addr.can_addr.isobus.addr = ISOBUS_GLOBAL_ADDR;

	/* SQLite goodies */
	if(sqlite3_open(arguments.fname, &db)) {
		fprintf(stderr, "SQLite3 error: %s\n", sqlite3_errmsg(db));
		sqlite3_close(db);
		return EXIT_FAILURE;
	}
	if(sqlite3_prepare_v2(db, SQL_STMT, -1, &stmt, NULL)) {
		fprintf(stderr, "Prepared statement failed.\n");
		return EXIT_FAILURE;
	}

	while(sqlite3_step(stmt) == SQLITE_ROW) {

		switch(sqlite3_column_text(stmt, 0)[0])
		{
		/* Send on engine bus */
		case 'e':
			sock = ((int *)socks)[0];
			break;

		/* Send on implement bus */
		case 't':
		case 'i':
			sock = ((int *)socks)[1];
			break;
		default:
			continue;
		}

		/* Construct message */
		mesg.pgn = sqlite3_column_int(stmt, 1);
		mesg.dlen = sqlite3_column_int(stmt, 3);
		memcpy(&mesg.data, sqlite3_column_blob(stmt, 2), mesg.dlen);

		/* Figure out when to send this message */
		cur_time = sqlite3_column_int64(stmt, 4);
		if(gettimeofday(&cur_tv, NULL)) {
			perror("gettimeofday");
			return EXIT_FAILURE;
		}
		delay = (cur_time - prev_time) -
			((cur_tv.tv_sec - prev_tv.tv_sec) * 1000000LL +
			 (cur_tv.tv_usec - prev_tv.tv_usec));
		if(delay > 0) {
			//printf("delay: %lld\n", delay);
			usleep(delay > arguments.max_delay ? arguments.max_delay : delay);
		}

		/* Send message */
		/* TODO: Set SA and DA based on log file */
		while(sendto(sock, &mesg, sizeof(mesg), 0, (struct sockaddr *)&addr,
					sizeof(addr)) < 0) {
			/* Wait briefly, try agian */
			usleep(1);
		}
		prev_time = cur_time;
		prev_tv = cur_tv;
	}

	/* Close stuff */
	sqlite3_finalize(stmt);
	sqlite3_close(db);
	return EXIT_SUCCESS;
}
示例#17
0
文件: SMTP.c 项目: jimiszm/peos
int sendmailto(char *smtphost,char *mailto,char *mailcc,
char *mailbcc,char *mailfrom,char *subject,char *content,recipient *head)
{
int tempreturn = 0;

simplesock s;

	if (mailto == NULL || strlen(mailto) == 0) return(0); 
	/* Exit if there are no recipient */

	s = init_socket(smtphost,25);
	if (strlen(s.errmessage) != 0) {
		fprintf(LOG," SMTP: %s\n",s.errmessage);
		return(0); 	// Unable to contact the server
	}

	if (okresponse(s,"2xx") == 0) return(0);

	fprintf(s.S_out,"HELO %s\n",smtphost);
	fflush(s.S_out);

	if (okresponse(s,"2xx") == 0) {
		sendquit(s);
		return(0);
	}

	fprintf(s.S_out,"MAIL FROM:<%s>\n",mailfrom);
	fflush(s.S_out);

	if (okresponse(s,"2xx") == 0) {
		sendquit(s);
		return(0);
	}

	if (mailto != NULL && strlen(mailto) > 0) 
		tempreturn = tempreturn + mult_send(s,mailto,MAILDELIM,head);
	if (mailcc != NULL && strlen(mailcc) > 0)
		tempreturn = tempreturn + mult_send(s,mailcc,MAILDELIM,head);
	if (mailbcc != NULL && strlen(mailbcc) > 0)
		tempreturn = tempreturn + mult_send(s,mailbcc,MAILDELIM,head);
	if (tempreturn == 0) {	// Don't have any available reciepient
		sendquit(s);
		return(0);
	}

	fprintf(s.S_out,"DATA\n"); // Send Data header
	fflush(s.S_out);

	if (okresponse(s,"354") == 0) {
		sendquit(s);
		return(0);
	}

	fprintf(s.S_out,"From: %s\n",mailfrom); /* Sending header lines */
	fprintf(s.S_out,"Subject: %s\n",subject);
	if (mailto != NULL) fprintf(s.S_out,"To: %s\n",mailto);
	if (mailcc != NULL) fprintf(s.S_out,"CC: %s\n",mailcc);
	fprintf(s.S_out,"Content-Type: text/plain; charset=us-ascii\n");
	fprintf(s.S_out,"Content-Transfer-Encoding: 7bit\n");
	submit_content(s,content);
	fprintf(s.S_out,"\n.\n");
	fflush(s.S_out);

	if (okresponse(s,"250") == 0) {
		sendquit(s);
		return(0);	// Error occurs
	}
	sendquit(s);
	return(1);
}
示例#18
0
 ListenThread::ListenThread(int port, std::queue<ProcessJobParams> *process_queue,
                  std::mutex *process_queue_mutex, std::condition_variable *cv_process_queue) :
   process_queue(process_queue), process_queue_mutex(process_queue_mutex), cv_process_queue(cv_process_queue)
 {
   init_socket(port);
 }
示例#19
0
static int load_module(xml_node *config) {

	xml_node *params, *profile=NULL, *settings;
	char *key, *value = NULL;
	unsigned int i = 0;
	//char module_api_name[256];
	char loadplan[1024];
	FILE* cfg_stream;

	LNOTICE("Loaded %s", module_name);

	load_module_xml_config();

	/* READ CONFIG */
	profile = module_xml_config;

	/* reset profile */
	profile_size = 0;

	while (profile) {

		profile = xml_get("profile", profile, 1);

		memset(&profile_socket[i], 0, sizeof(profile_socket_t));

		if (profile == NULL)
			break;

		if (!profile->attr[4] || strncmp(profile->attr[4], "enable", 6)) {
			goto nextprofile;
		}

		/* if not equals "true" */
		if (!profile->attr[5] || strncmp(profile->attr[5], "true", 4)) {
			goto nextprofile;
		}

		/* set values */
		profile_socket[profile_size].name = strdup(profile->attr[1]);
		profile_socket[profile_size].description = strdup(profile->attr[3]);
		profile_socket[profile_size].serial = atoi(profile->attr[7]);
		profile_socket[profile_size].protocol = PROTO_SIP; //we extract SIP and send as SIP packet
		profile_socket[profile_size].port = TZSP_PORT;
		profile_socket[profile_size].host = TZSP_HOST;
		
		/* SETTINGS */
		settings = xml_get("settings", profile, 1);

		if (settings != NULL) {

			params = settings;

			while (params) {

				params = xml_get("param", params, 1);
				if (params == NULL)
					break;

				if (params->attr[0] != NULL) {

					/* bad parser */
					if (strncmp(params->attr[0], "name", 4)) {
						LERR("bad keys in the config");
						goto nextparam;
					}

					key = params->attr[1];

					if (params->attr[2] && params->attr[3] && !strncmp(params->attr[2], "value", 5)) {
						value = params->attr[3];
					} else {
						value = params->child->value;
					}

					if (key == NULL || value == NULL) {
						LERR("bad values in the config");
						goto nextparam;

					}

					if (!strncmp(key, "host", 4))
						profile_socket[profile_size].host = strdup(value);
					else if (!strncmp(key, "port", 4))
						profile_socket[profile_size].port = strdup(value);
					else if (!strncmp(key, "protocol-type", 13))
						profile_socket[profile_size].protocol = atoi(value);						
					else if (!strncmp(key, "capture-plan", 12))
						profile_socket[profile_size].capture_plan = strdup(value);
				}

				nextparam: params = params->next;

			}
		}
		
		profile_size++;

		nextprofile: profile = profile->next;
	}

	/* free */		
		
	free_module_xml_config();

#if UV_VERSION_MAJOR == 0
    loop = uv_loop_new();
#else               
    loop = malloc(sizeof *loop);
    uv_loop_init(loop);
#endif

	for (i = 0; i < profile_size; i++) {

		if(profile_socket[i].capture_plan != NULL)
		{

			snprintf(loadplan, sizeof(loadplan), "%s/%s", global_capture_plan_path, profile_socket[i].capture_plan);
			cfg_stream=fopen (loadplan, "r");

			if (cfg_stream==0){
			   fprintf(stderr, "ERROR: loading config file(%s): %s\n", loadplan, strerror(errno));
			}

			yyin=cfg_stream;
			if ((yyparse()!=0)||(cfg_errors)){
			          fprintf(stderr, "ERROR: bad config file (%d errors)\n", cfg_errors);
			}

			profile_socket[i].action = main_ct.idx;
		}

		// start thread
		if (init_socket(i)) {
			LERR("couldn't init tzsp");
			return -1;
		}

		//pthread_create(&call_thread, NULL, proto_collect, arg);

	}
	
	uv_async_init(loop, &async_handle, _async_callback);
	uv_thread_create(&runthread, _run_uv_loop, loop);

	return 0;
}
示例#20
0
int main(int argc, char *argv[]) {
  int sock, i, c;
  int num_keys = 1;
  char* req_buf = (char*) malloc(BUFLEN);
  char* res_buf = (char*) malloc(BUFLEN);
  timeval t1, t2;
  int elapsedTime, num=0;
  int samples[NUM_SAMPLES];
  bool reuse_conn = true;

  /* Check parameters */
  while ((c=getopt(argc, argv, "f:t:v:h:p:k:c")) != -1) {
    switch (c) {
      case 'p':
        port = atoi(optarg);
        break;
      case 'h':
        host = strdup(optarg);
        break;
      case 'f':
        unix_socket = strdup(optarg);
        break;
      case 't':
        table = strdup(optarg);
        break;
      case 'v':
        version = atoi(optarg);
        break;
      case 'k':
        num_keys = atoi(optarg);
        break;
      case 'c':
        reuse_conn = false;
        break;
      case '?':
        if (optopt == 'h' || optopt == 'p' || optopt == 'k' ||
            optopt == 't' || optopt == 'v' || optopt == 'f')
          fprintf(stderr, "Option -%c requires an argument.\n", optopt);
        else
          fprintf(stderr, "Unknown option `-%c'.\n", optopt);
        return 1;
      default:
        return 1;
    }
  }

  if (table==NULL) table = strdup(TABLE_NAME);
  if (host==NULL) host = strdup(SRV_IP);

  sock = init_socket();
  srand(time(0));
  int* ids = (int*) malloc(sizeof(int) * num_keys);

  for (i=0; i<10000000; i++) {
    sprintf(req_buf, "get");
    char *current = req_buf + strlen(req_buf);
    for (int j=0; j<num_keys; j++) {
      int user_id = 60000000 + (rand()%10000000);
      int partition = user_id % 100;
      ids[j]=user_id;
      sprintf(current, " %s:%d@%d:%d", table,
          partition, version, user_id);
      current += strlen(current);
    }
    sprintf(current, "\n");

    // Send request
    gettimeofday(&t1, NULL);
    if (!reuse_conn) {
      close(sock);
      sock = init_socket();
    }

    int pending = strlen(req_buf);
    char* req_pos = req_buf;
    int sent = 0;
    do {
      sent = send(sock, req_pos, pending, 0);
      if (sent<=0)
        break;
      if (sent>0) {
        req_pos+=sent;
        pending-=sent;
      }
    } while(pending);

    if (sent==-1) {
      fprintf(stderr, "send() failed, errno=%i\n", errno);
      exit(1);
    }

    // get response
    int bytes = 0;
    int total = 0;
    do {
       bytes = recv(sock, res_buf+total, BUFLEN-total, 0);
       if (bytes<=0)
         break;
       if (bytes>0)
         total += bytes;
    } while (0!=strncmp(res_buf+total-5, "END\r\n", 5));

    if (bytes<0) {
      fprintf(stderr, "recv() failed errno=%d\n", errno);
    } else {
      gettimeofday(&t2, NULL);
      res_buf[total]=0;
      // compute and print the elapsed time in microsec
      elapsedTime = (t2.tv_sec - t1.tv_sec) * 1000000; 
      elapsedTime += (t2.tv_usec - t1.tv_usec); 
      fprintf(stderr, "Elapsed time: %d\n", elapsedTime);
      samples[num++]=elapsedTime;
      //fprintf(stderr, "%s\n", res_buf);
      check_results(ids, num_keys, res_buf);
    }
    if (num>=NUM_SAMPLES) {
      print_stats(samples, num);
      break;
    }
    usleep(200);
  }

  // Release resources
  close(sock);
  free(req_buf);
  free(res_buf);
  free(host);
  free(unix_socket);
  free(table);
  free(ids);

  return 0;
}
void M2MConnectionHandlerPimpl::dns_handler()
{
    palStatus_t status;
    palSocketLength_t _socket_address_len;

    tr_debug("M2MConnectionHandlerPimpl::dns_handler - _socket_state = %d", _socket_state);

    switch (_socket_state) {
        case ESocketStateConnectBeingCalled:
        case ESocketStateCloseBeingCalled:
            // Ignore these events
            break;

        case ESocketStateDisconnected:

            // Initialize the socket to stable state
            close_socket();

            status = pal_getAddressInfo(_server_address.c_str(), &_socket_address, &_socket_address_len);
            if (PAL_SUCCESS != status) {
                tr_error("addrInfo, err: %d", (int)status);
                _observer.socket_error(M2MConnectionHandler::DNS_RESOLVING_ERROR);
                return;
            }
            status = pal_setSockAddrPort(&_socket_address, _server_port);

            if (PAL_SUCCESS != status) {
                tr_error("setSockAddrPort err: %d", (int)status);
            } else {
                tr_debug("address family: %d", (int)_socket_address.addressType);
            }

            if (_socket_address.addressType == PAL_AF_INET) {
                status = pal_getSockAddrIPV4Addr(&_socket_address,_ipV4Addr);
                if (PAL_SUCCESS != status) {
                    tr_error("sockAddr4, err: %d", (int)status);
                    _observer.socket_error(M2MConnectionHandler::DNS_RESOLVING_ERROR);
                    return;
                }

                tr_debug("IPv4 Address %s", tr_array(_ipV4Addr, 4));

                _address._address = (void*)_ipV4Addr;
                _address._length = PAL_IPV4_ADDRESS_SIZE;
                _address._port = _server_port;
            }
            else if (_socket_address.addressType == PAL_AF_INET6) {
                status = pal_getSockAddrIPV6Addr(&_socket_address,_ipV6Addr);
                if (PAL_SUCCESS != status) {
                    tr_error("sockAddr6, err: %d", (int)status);
                    _observer.socket_error(M2MConnectionHandler::DNS_RESOLVING_ERROR);
                    return;
                }

                tr_debug("IPv6 Address %s", tr_array(_ipV6Addr,sizeof(_ipV6Addr)));

                _address._address = (void*)_ipV6Addr;
                _address._length = PAL_IPV6_ADDRESS_SIZE;
                _address._port = _server_port;
            }
            else {
                tr_error("socket config error, stack: %d", (int)_socket_address.addressType);
                _observer.socket_error(M2MConnectionHandler::SOCKET_ABORT);
                return;
            }

            if(!init_socket()) {
                tr_error("socket init error");
                // The init_socket() calls the socket_error() -callback directly, so it must not be
                // done here too.
                return;
            }

            if(is_tcp_connection()) {
#ifdef PAL_NET_TCP_AND_TLS_SUPPORT
                tr_debug("resolve_server_address - Using TCP");

                // At least on mbed-os the pal_connect() will perform callbacks even during it
                // is called, which we will ignore when this state is set.
                _socket_state = ESocketStateConnectBeingCalled;

                status = pal_connect(_socket, &_socket_address, sizeof(_socket_address));

                if (status == PAL_ERR_SOCKET_IN_PROGRES) {
                    // In this case the connect is done asynchronously, and the pal_socketMiniSelect()
                    // will be used to detect the end of connect.
                    // XXX: the mbed-os version of PAL has a bug (IOTPAL-228) open that the select
                    // does not necessarily work correctly. So, should we actually handle
                    // the PAL_ERR_SOCKET_IN_PROGRESS as a error here if code is compiled for mbed-os?
                    tr_debug("pal_connect(): %d, async connect started", (int)status);
                    // we need to wait for the event
                    _socket_state = ESocketStateConnecting;
                    break;

                } else if (status == PAL_SUCCESS) {

                    tr_info("pal_connect(): success");
                    _running = true;
                    _socket_state = ESocketStateConnected;

                } else {
                    tr_error("pal_connect(): failed: %d", (int)status);
                    close_socket();
                    _observer.socket_error(M2MConnectionHandler::SOCKET_ABORT);
                    return;
                }
#else
                tr_error("dns_handler() - TCP not configured"
#endif //PAL_NET_TCP_AND_TLS_SUPPORT
            } else {
                tr_debug("resolve_server_address - Using UDP");
                _socket_state = ESocketStateConnected;
                _running = true;
            }

        // fall through is a normal flow in case the UDP was used or pal_connect() happened to return immediately with PAL_SUCCESS
        case ESocketStateConnected:
            if (_security) {
                if (_security->resource_value_int(M2MSecurity::SecurityMode) == M2MSecurity::Certificate ||
                    _security->resource_value_int(M2MSecurity::SecurityMode) == M2MSecurity::Psk) {
                    if( _security_impl != NULL ){
                        _security_impl->reset();
                        if (_security_impl->init(_security) == 0) {
                            _is_handshaking = true;
                            tr_debug("resolve_server_address - connect DTLS");
                            if(_security_impl->start_connecting_non_blocking(_base) < 0 ){
                                tr_debug("dns_handler - handshake failed");
                                _is_handshaking = false;
                                close_socket();
                                _observer.socket_error(M2MConnectionHandler::SSL_CONNECTION_ERROR);
                                return;
                            }
                        } else {
                            tr_error("resolve_server_address - init failed");
                            close_socket();
                            _observer.socket_error(M2MConnectionHandler::SSL_CONNECTION_ERROR, false);
                            return;
                        }
                    } else {
                        tr_error("dns_handler - sec is null");
                        close_socket();
                        _observer.socket_error(M2MConnectionHandler::SSL_CONNECTION_ERROR, false);
                        return;
                    }
                }
            }
            if(!_is_handshaking) {
                enable_keepalive();
                _observer.address_ready(_address,
                                        _server_type,
                                        _address._port);
            }
            break;

        // This case is a continuation of a nonblocking connect() and is skipped
        // completely on UDP.
        case ESocketStateConnecting:

            // there is only one socket which we are interested
            uint8_t socketStatus[1];
            pal_timeVal_t zeroTime = {0, 0};
            uint32_t socketsSet = 0;

            status = pal_socketMiniSelect(&_socket, 1, &zeroTime, socketStatus, &socketsSet);
            if (status != PAL_SUCCESS) {
                // XXX: how could this fail? What to do?
                tr_error("dns_handler() - read select fail, err: %d", (int)status);
                close_socket(); // this will also set the socket state to disconnect
                // XXX: should we inform the observer here too?
                return;
            }

            if (socketsSet > 0) {
                if (PAL_NET_SELECT_IS_TX(socketStatus, 0)) {
                    // Socket is connected, signal the dns_handler() again to run rest of the steps
                    tr_debug("dns_handler() - connect+select succeeded");
                    _socket_state = ESocketStateConnected;
                    send_dns_event();
                } else if (PAL_NET_SELECT_IS_ERR(socketStatus, 0)) {
                    tr_error("dns_handler() - connect+select failed");
                    close_socket(); // this will also set the socket state to disconnect
                    // XXX: should we inform the observer here too?
                } else {
                    tr_debug("dns_handler() - connect+select not ready yet, continue waiting");
                }
            }
            break;
    }
int main(int argc, char* argv[])
{
 if (argc == 4) {
    leading_zeroes = atoi(argv[1]);
    jobs_per_time= atoi(argv[2]);    
    jobs_period= atoi(argv[3]);        
 } else {
    printf("Usage: %s <leading zeroes> <jobs per send> <send period milli>\n", argv[0]);
    return 0;
 }
 

    
 int  socket_fd = init_socket();
 passert(socket_fd != 0);

 
 
 minergate_req_packet* mp_req = allocate_minergate_packet_req(0xca, 0xfe);
 minergate_rsp_packet* mp_rsp = allocate_minergate_packet_rsp(0xca, 0xfe);
 int i;
 int requests = 0;
 int responces = 0;
 int rate = 0;
 int global_rate = 0; 
 int global_rate_cnt = 0; 
 
 //nbytes = snprintf(buffer, 256, "hello from a client");
 srand (time(NULL));

 while (1) {
  passert(jobs_per_time <= MAX_REQUESTS);
     for (i = 0; i < (jobs_per_time); i++) {
        minergate_do_job_req* p = mp_req->req+i;
        fill_random_work2(p);
    requests++;
    //printf("DIFFFFFFF %d\n", p->leading_zeroes);
     }
     mp_req->req_count = jobs_per_time;
     //printf("MESSAGE TO SERVER: %x\n", mp_req->request_id);
     send_minergate_pkt(mp_req,  mp_rsp, socket_fd);
     //printf("MESSAGE FROM SERVER: %x\n", mp_rsp->request_id);

   
    //DBG(DBG_NET, "GOT minergate_do_job_req: %x/%x\n", sizeof(minergate_do_job_req), md->data_length);
    int array_size = mp_rsp->rsp_count;
    int i;
    for (i = 0; i < array_size; i++) { // walk the jobs
       responces++;
       minergate_do_job_rsp* work = mp_rsp->rsp+i;
       if (work->winner_nonce[0]) {
         int job_difficulty = 1<<(leading_zeroes-32); // in 4GH units
         rate += job_difficulty;
       }
       if (work->winner_nonce[1]) {
         int job_difficulty = 1<<(leading_zeroes-32); // in 4GH units
         rate += job_difficulty;
       }

    }

   
   //printf("REQUESTS: %d RESPONCES: %d, DELTA: %d\n",requests, responces, requests - responces);
   usleep(jobs_period*1000);
   static int last_time = 0;
   int t = time(NULL);
   static int counter = 0;
   counter++;
   // Show rate each X seconds 
   if ((counter%((1000/jobs_period))) == 0) {
      global_rate+=rate;
      global_rate_cnt++;
      printf(MAGENTA "HASH RATE=%4dGH (TOTAL=%fGH) %d\n" RESET,rate*4,((4.0*(float)global_rate)/(float)global_rate_cnt), t-last_time);
      rate=0;
      last_time = t;
   }
 }
 close(socket_fd);
 free(mp_req);
 return 0;
}
int WolfSSLConnection::connect(const char* host, const int port)
{
    int result;
    
    if(sslContext == NULL)
    {
		LogError("NULL SSL context\r\n");
        result = __LINE__;
    }
    else
    {
        if (init_socket(SOCK_STREAM) < 0)
        {
			LogError("init_socket failed\r\n");
            result = __LINE__;
        }
        else
        {
            if (set_address(host, port) != 0)
            {
				LogError("set_address failed\r\n");
                result = __LINE__;
            }
            else if (lwip_connect(_sock_fd, (const struct sockaddr *) &_remoteHost, sizeof(_remoteHost)) < 0)
            {
                close();
				LogError("lwip_connect failed\r\n");
                result = __LINE__;
            }
            else
            {
                wolfSSL_SetIOSend(sslContext, &sendCallback);
                wolfSSL_SetIORecv(sslContext, &receiveCallback);
            
                ssl = wolfSSL_new(sslContext);
                if(ssl == NULL) 
                {
					LogError("wolfssl new error\r\n");
                    result = __LINE__;
                }
                else
                {
                    wolfSSL_set_fd(ssl, _sock_fd);
                
                    result = wolfSSL_connect(ssl);
                    if (result != SSL_SUCCESS) 
                    {
                        LogError("wolfssl connect error=%d\r\n", result);
                        result = __LINE__;
                    }
                    else
                    {
                        result = 0;
                        isConnected = true;
                    }
                }
            }
        }
    }

    return result;
};
示例#24
0
int main ()
{
	char message [512];
	int n = 1;
	int tps = 1;
	int wait =1;
	/*
	//handle the ctrl -c to make the drone land
	struct sigaction act;
	memset(&act,0,sizeof(act));
	act.sa_handler = intHandler;
	sigaction(SIGINT, &act, NULL);
	*/

    if (init_socket() != 0)
    {
        printf("[FAILED] Socket initialization failed\n");
    }
    else //complex_move(...;float roll_power, float pitch_power, float vertical_power, float yaw_power)
    {
		sleep(1);
    	printf("demarrage\n");
		set_trim(message, n++, wait);
		
		while(tps < 167)
		{
			take_off(message, n++, wait);
			tps++;
		}
		tps = 0;
		
		//test de fonction
		at_config(message, n++, "pic:ultrasound_freq","2");
		
		//while(tps < 133)
		//while(1)
		while(keepRunning)
		{
			reset_com(message, wait);
	 		tps++;
		}
		tps = 0;
/*
        printf("debut commande\n");

		while(tps < 500)
		{
			//go front and up and turning clockwise			
			set_complex_move(message,n++,0,-0.05,0.1,0.05,wait);
			tps++;
		}
		tps = 0;

		set_complex_move(message, n++,0,0,0,0,wait);
		while(tps < 133)
		{
			reset_com(message,wait);
	 		tps++;
		}
		tps = 0;
*/
		landing(message, n++,wait);
		sleep(1);

	}
    close(sockfd);
	return 0;
}
示例#25
0
文件: socket.c 项目: yaomoon/GT2440
int main(int argc, char *argv[])
{
	char c;
	int i,len;
	int server_sock;
	socklen_t client_len;
	struct sockaddr_in server,client;
	struct in_addr in;
	
    struct my_socket my_socket;

    init_curses();
    draw_bottom();

    init_socket(&my_socket);
    server_sock = get_udpsocket(&my_socket);

	// communication with client
	while(1)
	{
		// wait for client request
		client_len = sizeof(client);
		len = recvfrom(server_sock, buffer, BUFFER_SIZE, 0, (struct sockaddr *)&client, &client_len);
		if (len < 0)
		{
			close(server_sock);
			fprintf(stderr, "%s\n", strerror(errno));
			exit(EXIT_FAILURE);
		}
		else
		{
            //printf("recvfrom client ok!\n");
			in.s_addr = client.sin_addr.s_addr;
            //printf("client ip  : %s\n", inet_ntoa(in));
            //printf("client port: %d\n", ntohs(client.sin_port));
            //printf("\n");
		}

		// Quit flag
		if(buffer[0] == '.') break;

		// lower to upper	
        /*
		for(i=0; i<len; i++)
		{
			c = buffer[i];
			buffer[i] = toupper(c);
		}
	
        */
		// send back to client
        //printf("%s\n",buffer);
        fill_state("newmessage",buffer);
        refresh_state();
		sendto(server_sock, buffer, len, 0, (struct sockaddr *)&client, client_len);

        memset(buffer,0,sizeof(buffer));
	}

    //printf("Client close the socket\n");
	close(server_sock);

	exit(EXIT_SUCCESS);
}
示例#26
0
文件: rcsocks.c 项目: 54Pany/sSocks
void server_relay(int port, int listen, int ssl) {
    int soc_ec_cli = -1, soc_ec = -1, maxfd, res, nc;
    fd_set set_read;
    fd_set set_write;
    struct sockaddr_in addrS;


#ifdef _WIN32
    WSADATA wsaData;
    int wsaInit = WSAStartup(MAKEWORD(2,2), &wsaData);
    if (wsaInit != 0) {
        ERROR(L_NOTICE, "WSAStartup failed: %d\n", wsaInit);
        exit(1);
    }
#endif

    /* Init client tab */
    for (nc = 0; nc < MAXCLI; nc++)
        init_socket(&socks_pool[nc]);

    for (nc = 0; nc < MAXCLI; nc++)
        init_client (&tc[nc], nc, 0, NULL);

    TRACE(L_NOTICE, "server: set listening client socks relay ...");
    soc_ec = new_listen_socket (NULL, port, MAXCLI, &addrS);
    if (soc_ec < 0) goto fin_serveur;

    TRACE(L_NOTICE, "server: set server relay ...");
    soc_ec_cli = new_listen_socket (NULL, listen, MAXCLI, &addrS);
    if (soc_ec_cli < 0) goto fin_serveur;


#ifndef _WIN32
    if ( globalArgs.background == 1 ) {
        TRACE(L_NOTICE, "server: background ...");
        if ( daemon(0, 0) != 0 ) {
            perror("daemon");
            exit(1);
        }
    }

    bor_signal (SIGINT, capte_fin, SA_RESTART);

    /* TODO: Find a better way to exit the select and recall the init_select
     * SIGUSR1 is send by a thread to unblock the select */
    bor_signal (SIGUSR1, capte_usr1, SA_RESTART);
#endif


    while (boucle_princ) {
        init_select_reverse(soc_ec, soc_ec_cli, tc, &maxfd, &set_read, &set_write);

        res = select (maxfd+1, &set_read, &set_write, NULL,NULL);

        if (res > 0) {  /* Search eligible sockets */

            if (FD_ISSET (soc_ec, &set_read))
                new_connection_socket (soc_ec, socks_pool, ssl);

            if (FD_ISSET (soc_ec_cli, &set_read))
                new_connection_reverse (soc_ec_cli, tc, socks_pool);

            for (nc = 0; nc < MAXCLI; nc++) {
                dispatch_server(&tc[nc], &set_read, &set_write);
            }
        } else if ( res == 0) {
            /* If timeout was set in select and expired */
        } else if (res < 0) {
            if (errno == EINTR) ;  /* Received signal, it does nothing */
            else {
                perror ("select");
                goto fin_serveur;
            }
        }
    }

fin_serveur:
#ifdef HAVE_LIBSSL
    if (ssl == 1)
        ssl_cleaning();
#endif
    printf ("Server: closing sockets ...\n");
    if (soc_ec != -1) CLOSE_SOCKET(soc_ec);
    for (nc = 0; nc < MAXCLI; nc++) close_socket(&socks_pool[nc]);
    for (nc = 0; nc < MAXCLI; nc++) disconnection(&tc[nc]);

#ifdef _WIN32
    WSACleanup();
#endif
}
示例#27
0
文件: client.c 项目: holyhope/System
int connect_socket(int port, char* name) {
    struct sockaddr_in sock;
    int fd,i, max_sd;
    int fd_connect;
    fd_set master_set;
    int read_size;
    char buffer[256]={0};
    sock = init_socket(port, name);
    if (-1 == (fd = socket(AF_INET, SOCK_STREAM, 0))) {
        perror("SOCKET");
        exit (EXIT_FAILURE);
    }
    if (-1
            == (fd_connect = connect(fd, (struct sockaddr*) &sock, sizeof(sock)))) {
        perror("CONNECT");
        exit (EXIT_FAILURE);
    }
   	if(-1 == write(1,"Communication ouverte avec le server\n",37)){
   		error_message("write");
   	}
    do {
        FD_ZERO(&master_set);
        max_sd = fd;
        FD_SET(fd, &master_set);
        FD_SET(STDIN_FILENO, &master_set);
 
        for(i = 0; i < SIZE ; i++){
            buffer[i] = '\0';
        }
        if(-1 == (select(max_sd +1, &master_set, NULL, NULL, NULL))) {
            perror("SELECT");
            exit(EXIT_FAILURE);
        }
 
            if(FD_ISSET(STDIN_FILENO, &master_set)){
                do {
                    if (-1 == (read_size = read(STDIN_FILENO, buffer, SIZE-6))) {
                        perror("read");
                        exit (EXIT_FAILURE);
                    }
                    if(read_size > SIZE-7) {
                        printf("Message trop long\n");
                    }
                }while(read_size > SIZE-7);
 
                strcat(buffer, "\n\0");
                send(fd, buffer, read_size+1, 0);
            }
            if(FD_ISSET(fd, &master_set)){
                if (-1 == (read_size = recv(fd, buffer, SIZE, 0))) {
                    perror("read");
                    exit (EXIT_FAILURE);
                }
                 
                if(-1 == write(STDOUT_FILENO, buffer, SIZE)){
                    perror("WRITE");
                    exit(EXIT_FAILURE);
                }
            }
    } while (1);
 
}
示例#28
0
文件: client.c 项目: ktht/UDP-test
int main(int argc, char ** argv) {

    /* handle ^C behavior */
    signal(SIGINT, intHandler);

    /* parse command line arguments */
    int cmd_flag, err_count = 0, server_addr_given = 0;
    while ((cmd_flag = getopt(argc, argv, ":s:p:i:n:w:t:P:f:mblrS")) != -1) {
        switch (cmd_flag) {
            case 's':
                server_addr_given = 1;
                strcpy(server_addr_name, optarg);
                break;
            case 'p':
                port_number   = strtol(optarg, NULL, 10);
                break;
            case 'i':
                interval      = strtoul(optarg, NULL, 10);
                break;
            case 'n':
                max_responses = strtoul(optarg, NULL, 10);
                break;
            case 'w':
                timeout       = strtoul(optarg, NULL, 10);
                break;
            case 't':
                socket_tos    = strtoul(optarg, NULL, 10);
                break;
            case 'P':
                payload_size  = strtoul(optarg, NULL, 10);
                break;
            case 'f':
                log_file = fopen(optarg, "w");
                break;
            case 'm':
                enable_multicast = TRUE;
                break;
            case 'b':
                enable_broadcast = 1;
                break;
            case 'l':
                enable_loopback  = 1;
                break;
            case 'r':
                record_sys_clock = TRUE;
                break;
            case 'S':
                send_only        = TRUE;
                break;
            case ':':
                fprintf(stderr, "Option -%c requires an operand.\n", optopt);
                ++err_count;
                break;
            case '?':
                fprintf(stderr, "Unrecognized option: -%c\n", optopt);
                ++err_count;
                break;
        }
    }
    if (err_count > 0 || port_number == -1 || server_addr_given == 0) {
        fprintf(stderr, USAGE("%s"), argv[0]);
        exit(EXIT_FAILURE);
    }

    /* print information */
    LOG("Server address:        %s\n",   server_addr_name);
    LOG("Port number:           %i\n",   port_number);
    LOG("Packet interval (ns):  %llu\n", interval);
    LOG("Max number of packets: %llu\n", max_responses);
    LOG("Socket timeout (ms):   %llu\n", timeout);
    LOG("Socket ToS:            %u\n",   socket_tos);
    LOG("Payload size:          %u\n",   payload_size);
    LOG("Enable multicast:      %s\n",   enable_multicast ? "yes" : "no");
    LOG("Enable broadcast:      %s\n",   enable_broadcast ? "yes" : "no");
    LOG("Enable loopback:       %s\n",   enable_loopback  ? "yes" : "no");
    LOG("Record system clock:   %s\n",   record_sys_clock ? "yes" : "no");
    LOG("Send only mode:        %s\n",   send_only        ? "yes" : "no");

    /* create socket */
    struct sockaddr_in server_addr, rcv_addr;
    socklen_t server_addr_size = sizeof(struct sockaddr_in);
    socklen_t rcv_addr_size    = sizeof(struct sockaddr_in);

    /* initialize socket */
    LOG("Initialize socket.\n");
    init_socket(& server_addr, server_addr_name, port_number);
    if ((udp_socket = socket(PF_INET, SOCK_DGRAM, IPPROTO_UDP)) == -1) {
        fprintf(stderr, "Error initializing UDP socket.\n");
        exit(EXIT_FAILURE);
    }

    /* set ToS */
    int tos = (socket_tos & 0x3F) << 2;
    if (tos) {
        if(setsockopt(udp_socket, IPPROTO_IP, IP_TOS, & tos, sizeof(tos)) < 0)
            fprintf(stderr, "Failed to set IP_TOS to %i.\n", tos);
    }

    /* add to broad/multicast if possible */
    if (enable_multicast) {
        mcast_add_membership_on_socket(udp_socket, server_addr_name);
    }
    mcast_enable_loop_on_socket(udp_socket, enable_loopback);
    bcast_enable_on_socket(udp_socket, enable_broadcast);

    /* set timeout */
    const u_int  timeout_s  = (u_long) (timeout / 1E3);
    const u_long timeout_us = (timeout % (u_long) 1E3) * (u_long) 1E3;
    timeout_set_on_socket(udp_socket, timeout_s, timeout_us);

    /* set time variables */
    struct timespec sent_time;
    clock_gettime(AVAILABLE_MONOTONIC_CLOCK, & sent_time);

    /* talk to server */
    LOG("Start communicating with the server.\n");
    int  read_size = 0;
    u_ll seq_num   = 0;
    while (TRUE) {

        /* get current time */
        struct timespec present_time;
        clock_gettime(AVAILABLE_MONOTONIC_CLOCK, & present_time);

        /* if enough time is passed */
        if ((present_time.tv_nsec + present_time.tv_sec * 1E9) -
            (sent_time.tv_nsec + sent_time.tv_sec * 1E9) >= interval) {

            /* construct the message */
            struct message msg;
            msg.header  = MSG_HEADER;
            msg.sec     = present_time.tv_sec;
            msg.nsec    = present_time.tv_nsec;
            msg.seq_num =
                #ifdef ARM
                    swap_uint64(seq_num)
                #else
                    seq_num
                #endif
            ;
            ++seq_num;

            /* send the packet */
            if (sendto(udp_socket, &msg, sizeof(struct message) + payload_size, 0,
                    (struct sockaddr *) & server_addr, server_addr_size) == -1) {
                fprintf(stderr, "Error on sending UDP packet.\n");
            }

            /* get current time */
            clock_gettime(AVAILABLE_MONOTONIC_CLOCK, & present_time);

            /* save sent time */
            sent_time = present_time;

            LOG("Sent packet number %llu to %s.\n", seq_num - 1, server_addr_name);

            const struct message * response = NULL;
            if (send_only != 1) {
                /* get response from the server/multicast address */
                read_size = recvfrom(udp_socket, buffer, BUFFER_SIZE, 0,
                                    (struct sockaddr *) & rcv_addr, & rcv_addr_size);
                if (read_size < 1)
                    break;
                response = (struct message *) buffer;
                LOG("Received packet nr %llu from %s.\n", seq_num - 1, server_addr_name);

                /* check if the packet has gone missing */
                u_ll response_seq_num =
                    #ifdef ARM
                        swap_uint64(response -> seq_num)
                    #else
                        response -> seq_num
                    #endif
                ;
                if (response_seq_num != seq_num - 1) {
                    fprintf(stderr, "Packet no %llu has gone missing.\n", seq_num - 1);
                    ++missing_packages;
                }
                ++total_responses;
            }

            /* write results */
            if (log_file) {
                if (record_sys_clock) {
                    const u_ll current_time = present_time.tv_sec * 1E9 +
                                              present_time.tv_nsec;
                    fprintf(log_file, "%llu,%llu\n", seq_num - 1, current_time);
                }
                else {
                    const u_ll time_difference =
                                  (present_time.tv_sec - response -> sec) * 1E9 +
                                  (present_time.tv_nsec - response -> nsec);
                    fprintf(log_file, "%llu,%.3f\n", seq_num - 1, time_difference / 1E3);
                }
                fflush(log_file);
            }

            /* terminate if enough sent */
            if (total_responses >= max_responses && max_responses)
                break;
        }
    }

    intHandler(EXIT_SUCCESS);

    return EXIT_SUCCESS;
}
示例#29
0
/**
 * The main program
 *
 * Parameters:
 *	 - int argc  => The number of arguments passed
 *	 - char** args  => The arguments list
 *
 * Return:
 *	 - int  => The result of the execution
 */
int main(int argc, char** args) {

	/* 	################################################## Initialisations ################################################## */
	// If there are too many arguments
	if (argc > 1) { perror("There are too many arguments. This program requires none"); return 1; }

	
	/* ##### Network structures ##### */
	// Socket creation and bind
	int server_socket = init_socket();

	// The variable to store datas received
	struct packet packet_received;
	struct packet packet_to_send;
	char buffer[BUFFER_SIZE];

	// The structure to store the source informations
	struct sockaddr_in source;
	socklen_t source_length = (socklen_t)sizeof(struct sockaddr);

	// To know the current state of the server
	int server_state = S_FREE;


	/* ##### Audio reader parameters ##### */
	// Some more variables that we'll need to read the audio file
	int sample_rate, sample_size, channels;
	int read_audio, read_init_audio = 0;


	/* ##### Timeout parameters ##### */
	int nb;
	fd_set watch_over;
	struct timeval timeout;



	/* 	################################################## Serve clients ################################################## */
	while (1) {  // Server always running
		
		// Clear and initialize the fd set
		FD_ZERO(&watch_over);
		FD_SET(server_socket, &watch_over);
		timeout.tv_sec = TIMEOUT_SERVER;  // 5 sec
		timeout.tv_usec = 0;
		nb = select(server_socket+1, &watch_over, NULL, NULL, &timeout);

		// If error during the select
		if (nb < 0) {
			perror("Can't attach the select to the file descriptor");
			return 1;
		}

		// Just consider the client is gone if timeout reached
		if (nb == 0) {
			server_state = S_FREE;
		}

		// If open, just act normally
		if (FD_ISSET(server_socket, &watch_over)) {

			// Clear packets
			clear_packet(&packet_to_send);
			clear_packet(&packet_received);

			// Wait a packet
			if (recvfrom(server_socket, &packet_received, sizeof(struct packet), 0, (struct sockaddr*)&source, &source_length) != -1) {

				// In function of the type of the packet received
				switch (packet_received.type) {

					// --------------- Receiving the filename ---------------
					case P_FILENAME:

						// If the server is busy, refuse the client asking for a file (it's the first packet sent)
						if (server_state == S_BUSY)
							server_error_encountered(server_socket, P_SERVER_ERROR, "Server busy for the moment. Please try later", (struct sockaddr*)&source, NULL);

						// If not busy, then put this client as the current
						else {
							
							// Put the server busy
							server_state = S_BUSY;

							// Initialize by getting informations about the music to play
							read_init_audio = aud_readinit(packet_received.message, &sample_rate, &sample_size, &channels);

							// If an error happened (maybe the file doesn't exist)
							if (read_init_audio == -1)
								server_error_encountered(server_socket, P_SERVER_ERROR, "Error at opening the audio file, the file requested may be inexistant", (struct sockaddr*)&source, &server_state);

							// If none
							else {

								// Store informations about this file
								snprintf(buffer, sizeof(buffer), "%d %d %d", sample_rate, sample_size, channels);

								// Create the packet to send
								create_packet(&packet_to_send, P_FILE_HEADER, buffer);

								// Send it
								if (sendto(server_socket, &packet_to_send, sizeof(struct packet), 0, (struct sockaddr*)&source, source_length) == -1)
									server_error_encountered(server_socket, P_ERR_TRANSMISSION, "Error at sending the file header", (struct sockaddr*)&source, &server_state);
							}
						}
						break;


					// --------------- Client requesting another block ---------------
					case P_REQ_NEXT_BLOCK:

						// Fill the buffer
						read_audio = read(read_init_audio, buffer, BUFFER_SIZE);

						// If the end of file is reached
						int type = P_BLOCK;
						if (read_audio != BUFFER_SIZE)
							type = P_EOF;

						// Create the packet to send
						create_packet(&packet_to_send, type, buffer);

						// And send it
						if (sendto(server_socket, &packet_to_send, sizeof(struct packet), 0, (struct sockaddr*)&source, source_length) == -1)
							server_error_encountered(server_socket, P_ERR_TRANSMISSION, "Error at sending the next block", (struct sockaddr*)&source, &server_state);

						break;


					// --------------- Client requesting the same packet (if it doesn't received it) ---------------
					case P_REQ_SAME_PACKET:

						// Resend packet previously created
						if (sendto(server_socket, &packet_to_send, sizeof(struct packet), 0, (struct sockaddr*)&source, source_length) == -1)
							server_error_encountered(server_socket, P_ERR_TRANSMISSION, "Error at sending the same block", (struct sockaddr*)&source, &server_state);

						break;


					// --------------- Client received correctly the close transmission ---------------
					case P_CLOSED:

						// Close the descriptor file when it's done
						if ((read_init_audio > 0) && (close(read_init_audio) != 0)) perror("Error at closing the read file descriptor");

						// Free the server
						server_state = S_FREE;

						break;
				}
			}

			// If an error during the receiving of a packet
			else
				server_error_encountered(server_socket, P_ERR_TRANSMISSION, "Error during the receiving of a packet", (struct sockaddr*)&source, &server_state);

		}

	}

	// Then close the socket
	if (close(server_socket) == -1) { perror("Error during the closing of the server socket"); return 1; }

	// If everything's was ok
	return 0;
}
示例#30
0
netplay_t *netplay_new(const char *server, uint16_t port,
      unsigned frames, const struct retro_callbacks *cb,
      bool spectate,
      const char *nick)
{
   unsigned i;
   if (frames > UDP_FRAME_PACKETS)
      frames = UDP_FRAME_PACKETS;

   netplay_t *handle = (netplay_t*)calloc(1, sizeof(*handle));
   if (!handle)
      return NULL;

   handle->fd = -1;
   handle->udp_fd = -1;
   handle->cbs = *cb;
   handle->port = server ? 0 : 1;
   handle->spectate = spectate;
   handle->spectate_client = server != NULL;
   strlcpy(handle->nick, nick, sizeof(handle->nick));

   if (!init_socket(handle, server, port))
   {
      free(handle);
      return NULL;
   }

   if (spectate)
   {
      if (server)
      {
         if (!get_info_spectate(handle))
            goto error;
      }

      for (i = 0; i < MAX_SPECTATORS; i++)
         handle->spectate_fds[i] = -1;
   }
   else
   {
      if (server)
      {
         if (!send_info(handle))
            goto error;
      }
      else
      {
         if (!get_info(handle))
            goto error;
      }

      handle->buffer_size = frames + 1;

      init_buffers(handle);
      handle->has_connection = true;
   }

   return handle;

error:
   if (handle->fd >= 0)
      close(handle->fd);
   if (handle->udp_fd >= 0)
      close(handle->udp_fd);

   free(handle);
   return NULL;
}