Exemple #1
0
int listen_for_connections(struct connection *server, int port, int tries)
{

	int i;

	if(port > 0)
		set_connection_port(server, port);

	if((server->socketfd = socket(AF_INET, SOCK_STREAM, 0)) == -1){
		fprintf(stderr, "could not create a socket!\n");
		return -1;
	}

	i = 1;
  	if(setsockopt(server->socketfd, SOL_SOCKET, SO_REUSEADDR, &i, sizeof(i)) == -1){
        	fprintf(stderr, "WARNING: Could not set socket for reuse!\n");
		fprintf(stderr, "WARNING: This may affect restarting the sensor when there are active TCP connections to it!\n");
	}

	memset(&server->sin, 0, sizeof(server->sin));
	server->sin.sin_family = AF_INET;
	server->sin.sin_addr.s_addr = htonl(INADDR_ANY);
	server->sin.sin_port = htons((unsigned short) server->port);

	for(i = 0; i < tries; i++) {
		if(!bind
		   (server->socketfd, (struct sockaddr *) &(server->sin),
			sizeof(server->sin)))
			break;
		fprintf(stderr, "Could not bind to port %d. ", server->port);
		if(i < tries)
			fprintf(stderr, "Will try %d more times...\n", tries-i);
		sleep(1);
	}

	if(i == 5) {
		fprintf(stderr, "Could not bind to port %d. Giving up!\n",
				server->port);
		return -1;
	}

	if(listen(server->socketfd, 50) < 0) {
		fprintf(stderr, "Error: listen()\n");
		close(server->socketfd);
		return -1;
	}

	return 0;
}
Exemple #2
0
int listen_for_connections(struct connection *server, int port, int tries)
{

	int i;

	if(port > 0)
		set_connection_port(server, port);

	server->socketfd = socket(AF_INET, SOCK_STREAM, 0);
	memset(&server->sin, 0, sizeof(server->sin));
	server->sin.sin_family = AF_INET;
	server->sin.sin_addr.s_addr = htonl(INADDR_ANY);
	server->sin.sin_port = htons((unsigned short) server->port);

	for(i = 0; i < tries; i++) {
		if(!bind
		   (server->socketfd, (struct sockaddr *) &(server->sin),
			sizeof(server->sin)))
			break;
		fprintf(stderr, "Could not bind to port %d. ", server->port);
		if(i < tries)
			fprintf(stderr, "Will try %d more times...\n", tries-i);
		sleep(1);
	}

	if(i == 5) {
		fprintf(stderr, "Could not bind to port %d. Giving up!\n",
				server->port);
		return -1;
	}

	if(listen(server->socketfd, 50) < 0) {
		fprintf(stderr, "Error: listen()\n");
		close(server->socketfd);
		return -1;
	}

	return 0;
}