Exemple #1
0
int connect_request(REQUEST* req){
	if(SDLNet_ResolveHost(&req->ip,req->host,req->host_port)==-1){
	    printf("connect_request: %s\n", SDLNet_GetError());
	    return false;
	}

	req->sock = SDLNet_TCP_Open(&req->ip);
	if(!(req->sock)){
		printf("connect_request: %s\n", SDLNet_GetError());
		return false;
	}
	req->connected = true;
	return true;
}
Exemple #2
0
void initialisationReseau(char *strip,void (*backData)(Data*),void (*backList)(DataList*),void (*backGame)(DataGame*))
{

    mCData = backData;
    mCList= backList;
    mCGame= backGame;
    isQuitting=false;
    printf("initialisationReseau: test\n");
    if(isNetInitialised())
    {
        printf("initialisationReseau: réseau djà initialisé: libération des ressources\n");
        sendQuit();
        printf("Waiting for reception thread to reconnect\n");
        int threadReturnValue;
        SDL_WaitThread(threadRecept, &threadReturnValue);
        printf("\nThread returned value: %d\n", threadReturnValue);
        SDLNet_TCP_Close(sd);
    }
    else
    {
    if (SDLNet_Init() < 0)
    {
        printf("SDLNet_Init: %s\n", SDLNet_GetError());
        return;
    }
    bufferLock = SDL_CreateMutex();
    }
    /* Resolve the host we are connecting to */
    if (SDLNet_ResolveHost(&ip, strip, PORT) < 0)
    {
        printf("Can't resolve host: %s\n", SDLNet_GetError());
        return;
    }

    /* Open a connection with the IP provided (listen on the host's port) */
    if (!(sd = SDLNet_TCP_Open(&ip)))
    {
        printf("Can't open tcp connecting: %s\n", SDLNet_GetError());
        return;
    }


    if(!bufferLock)
    {
        printf("initialisationReseau: ERROR can't create mutex\n");
    }
    //canRecept = SDL_CreateCond();
    //canSend = SDL_CreateCond();
    networkinitialised = 1;
}
Exemple #3
0
void Networking::serverConnect(){
  SDLNet_Init();
  if(SDLNet_ResolveHost(&serv_ip, NULL, PORT) == -1) {
    printf("SDLNet_ResolveHost: %s\n", SDLNet_GetError());
    exit(0);
  }
  server_socket = SDLNet_TCP_Open(&serv_ip);
  if(!server_socket){
    printf("SDLNet_TCP_Open: %s\n", SDLNet_GetError());
    exit(0);
  }

  server_socketset = SDLNet_AllocSocketSet(3);
}
//string mythVirtualServer::GetLocalAddress(){
//	unsigned char iphost[4] = { 0 };
//	IPaddress serverip;
//	SDLNet_GetLocalAddress(&serverip);
//	SDL_memcpy(iphost, &serverip.host, 4);
//	char tmpstr[100] = { 0 };
//	sprintf(tmpstr, "%d.%d.%d.%d", iphost[0], iphost[1], iphost[2], iphost[3]);
//	return tmpstr;
//}
int mythVirtualServer::initalsocket(int port){
	
    IPaddress serverIP;
	int i;
	unsigned char iphost[4] = {0};

        /* Initialize SDL */
    if ( SDL_Init(0) < 0 ) {
		fprintf(stderr, "Couldn't initialize SDL: %s\n",SDL_GetError());
        exit(1);
    }

    /* Initialize the network */
    if ( SDLNet_Init() < 0 ) {
        fprintf(stderr, "Couldn't initialize net: %s\n",
                        SDLNet_GetError());
        SDL_Quit();
        exit(1);
    }
#pragma omp parallel for
    /* Initialize the channels */
    for ( i=0; i<CHAT_MAXPEOPLE; ++i ) {
		people[i] = PEOPLE::CreateNew();
		people[i]->addtionaldata = NULL;
		people[i]->active = 0;
		people[i]->sock = NULL;
    }

    /* Allocate the socket set */
    socketset = SDLNet_AllocSocketSet(CHAT_MAXPEOPLE+1);
    if ( socketset == NULL ) {
        fprintf(stderr, "Couldn't create socket set: %s\n",
                        SDLNet_GetError());
        cleanup(2);
    }

    /* Create the server socket */
	SDLNet_ResolveHost(&serverIP, NULL, port);
	//iphost[0] = &serverIP.host;
	SDL_memcpy(iphost, &serverIP.host, 4);
	printf("Server IP: %d.%d.%d.%d ---  %d\n", iphost[0], iphost[1], iphost[2], iphost[3], port);
    servsock = SDLNet_TCP_Open(&serverIP);
    if ( servsock == NULL ) {
        fprintf(stderr, "Couldn't create server socket: %s\n",
                        SDLNet_GetError());
        cleanup(2);
    }
    SDLNet_TCP_AddSocket(socketset, servsock);
	return 0;
}
Exemple #5
0
void Server::connect(Universe *_u){
    u = _u;
    SDLNet_Init();
    SDLNet_ResolveHost(&ip,server,port);
    sock = SDLNet_TCP_Open(&ip);
    if (!sock){
        printf("could not connect to %s:%d\n",server,port);
        return;
    }
    set = SDLNet_AllocSocketSet(1);
    SDLNet_TCP_AddSocket(set,sock);
    send("name %s\n",myname);
    last_ping_time = SDL_GetTicks();
}
Exemple #6
0
bool TCPConnection::ResolveHost()
{
	int success = 0;
	std::string serverOrClient;

	if ( isServer )
	{
		// IP is null becasue this is a server
		// Port is listening port
		success = SDLNet_ResolveHost( &ipAddress, nullptr, portNr );
		serverOrClient = "server";
	}
	else
	{
		// IP is the IP of the server
		// Port is the port the serer listens on ( seea above )
		success = SDLNet_ResolveHost( &ipAddress, hostName.c_str(), portNr );
		serverOrClient = "client";
	}

	std::stringstream ss("");
	ss	<<  serverOrClient << "-" << hostName << " : " << portNr;
	logger->Log( __FILE__, __LINE__, "Resolving host : ", ss.str() );

	if ( success == -1 )
	{
		ss.str("");
		ss	<<  hostName << " : " << portNr <<" Error : " << SDLNet_GetError();
		logger->Log( __FILE__, __LINE__, "Failed to resolve host : ", ss.str() );

		return false;
	}

	logger->Log( __FILE__, __LINE__, "Host resolved!"  );

	return true;
}
Exemple #7
0
cearth_ctx *
cearthctx_new(void)
{
        cearth_ctx *ctx = calloc(1, sizeof(cearth_ctx));
        /* Connect to server. */
        ctx->sk = SDLNet_UDP_Open(0);

        IPaddress ip;
        SDLNet_ResolveHost(&ip, haven_serv, HAVENSERV_PORT);

        int success = SDLNet_UDP_Bind(ctx->sk, -1, &ip);
        /* TEST */
        printf("Success: %d\n", success);
        return ctx;
}
int common_connect_server(IPaddress *host_ipaddress,TCPsocket *server_socket,Uint16 port,const char *host)
{
	if(SDLNet_ResolveHost(host_ipaddress,host,port)!=0)
	{
		printf("\nUnable to initialize ipaddress for server");
		return 0;
	}
	printf("\n I am listening on port %d",port);
	if(!(*server_socket=SDLNet_TCP_Open(host_ipaddress)))
	{	
		printf("\nUnable to initialize server socket:%s",SDLNet_GetError());
		return 0;
	}
	return 1;
}
Exemple #9
0
void TTCPServerSocket::listen (Uint16 port) {
	IPaddress ip;

	/* ip.host = INADDR_ANY */
	if(SDLNet_ResolveHost(&ip,NULL,port) == -1) {
		std::cerr << "SDLNet_ResolveHost: "<< SDLNet_GetError() << std::endl;
		exit(1);
	}
	/*  poslouchame pro prichozi spojeni z port-u*/
	serversock=SDLNet_TCP_Open(&ip);
	if(!serversock) {
		std::cerr << "SDLNet_TCP_Open: " << SDLNet_GetError() << std::endl;
		exit(2);
	} else listening = true;
}
Exemple #10
0
void ClientConnection::initialize_connection() {
	IPaddress ip;
	if (SDLNet_ResolveHost(&ip, hostname.c_str(), _port) < 0) {
		fprintf(stderr, "Error resolving host name '%s'\n", hostname.c_str());
	} else {
		_client_socket = SDLNet_TCP_Open(&ip);
		if (!_client_socket) {
			fprintf(stderr,
					"Error resolving connecting to host '%s' with port %d\n",
					hostname.c_str(), _port);
		}

		SDLNet_TCP_AddSocket(_socket_set, _client_socket);
	}
}
Exemple #11
0
bool net_init()
{
    if ( SDLNet_Init() < 0 ) {
	    printf("SDLNet_Init: %s\n", SDLNet_GetError());
	    return false;
	}
	
	atexit(SDLNet_Quit);

	IPaddress ip;
	SDLNet_ResolveHost(&ip, "happy", 12521);
	sprintf(szIPString, "%d.%d.%d.%d", ip.host & 0xff, (ip.host >> 8) & 0xff, (ip.host >> 16) & 0xff, (ip.host >> 24) & 0xff);

	return true;
}
Exemple #12
0
/* perform initialization and start up game loop */
int main(int argc, char *argv[])
{
	int rval;
	/* start up SDL and create window */
	if (init() < 0) {
		fprintf(stderr, "failed to initialize!\n");
		rval = 1;
		goto exit;
	}
	/* load media */
	if (load_media() < 0) {
		fprintf(stderr, "failed to load media!\n");
		rval = 1;
		goto exit;
	}
	/* networking setup */
	/* these definitions need to be put in the global space */
	IPaddress ip;
	TCPsocket server = NULL;
	TCPsocket client = NULL;
	if (SDLNet_ResolveHost(&ip, NULL, 9999) < 0) {
		fprintf(stderr, "SDLNet_ResolveHost: %s\n",
				SDLNet_GetError());
		rval = 1;
		goto exit;
	}
	server = SDLNet_TCP_Open(&ip);
	if (!server) {
		fprintf(stderr, "SDLNet_TCP_Open: %s\n",
				SDLNet_GetError());
		rval = 1;
		goto exit;
	}
	/* now listen for client */
	goto exit;
	while (!client) {
		SDL_Delay(0);
		client = SDLNet_TCP_Accept(server);
	}
	/* start game loop */
	printf("starting loop\n");
	game_loop();
	rval = 0;
exit:
	/* free resources and close SDL */
	cleanup();
	return rval;
}
void Server::sendQuery(const char* linkQuery) {
    answer.clear();
    if (SDLNet_ResolveHost(&hostIP, host, hostPort)) {
        errorState = SERVER_RESOLVE_ERROR;
        printErrorState(errorState, __LINE__);
        return;
    }
    socket = SDLNet_TCP_Open(&hostIP);
    logger("%d", socket);
    if (socket == NULL) {
        errorState = SOCKET_OPEN_ERROR;
        printErrorState(errorState, __LINE__);
        logger("%s", SDLNet_GetError());
        exit(0);
        return;
    }
    char *query = (char *) new char[HEAD_QUERY_SIZE + strlen(linkQuery) + TAIL_QUERY_SIZE];
    char *answerBuffer = (char *) new char[STANDARD_QUERY_SIZE];
    memset(query, 0, strlen(query));

    strcat(query, HEAD_QUERY_STRING);
    strcat(query, linkQuery);
    strcat(query, TAIL_QUERY_STRING);

    if (!(SDLNet_TCP_Send(socket, query, strlen(query)) != strlen(query))) // Ушли ли все данные? да-спрашиваем нет-в логгер.
        while (true) { // пока данные поступают.
            counters = SDLNet_TCP_Recv(socket, answerBuffer, STANDARD_QUERY_SIZE / 6); // 6 - unicodeLen 
            if (counters < 0) {
                errorState = SOCKET_CONNECT_ERROR;
                printErrorState(errorState, __LINE__);
                break;
            }
            if (counters == 0) {
                errorState = RECV_CLOSE_SUCCESSFUL;
                printErrorState(errorState, __LINE__);
                break;
            }
            for (unsigned int i = 0; i < counters; i++) answer.push_back(answerBuffer[i]);
        } else {
        errorState = QUERY_SEND_ERROR;
        printErrorState(errorState, __LINE__);

    }
    delete[] query;
    delete[] answerBuffer;
    SDLNet_TCP_Close(socket);
    socket = NULL;
}
Exemple #14
0
bool IPX_StartServer(Bit16u portnum) {
	Bit16u i;

	if(!SDLNet_ResolveHost(&ipxServerIp, NULL, portnum)) {
	
		//serverSocketSet = SDLNet_AllocSocketSet(SOCKETTABLESIZE);
		ipxServerSocket = SDLNet_UDP_Open(portnum);
		if(!ipxServerSocket) return false;

		for(i=0;i<SOCKETTABLESIZE;i++) connBuffer[i].connected = false;

		TIMER_AddTickHandler(&IPX_ServerLoop);
		return true;
	}
	return false;
}
Exemple #15
0
TCPsocket rocsmq_init(p_rocsmq_baseconfig server) {
	TCPsocket sock;
	IPaddress ip;
	
	/* create client information */
	t_rocsmq_message message;
	message.id[0] = '\0';
	strncpy(message.sender,server->clientname,ROCS_CLIENTNAMESIZE);

		p_rocsmq_clientdata cdata = (p_rocsmq_clientdata) message.tail;
		strncpy(cdata->filter,server->filter, ROCS_IDSIZE);
		strncpy(cdata->name,server->clientname,ROCS_CLIENTNAMESIZE);



	/*
	 * verbindung aufbauen
	 */
	/* initialize SDL_net */
	if(SDLNet_Init()==-1) return 0;

	if(SDLNet_ResolveHost(&ip,server->serverip,server->port)==-1)
	{
		SDLNet_Quit();
		return 0;
	}

	/* open the server socket */
	sock=SDLNet_TCP_Open(&ip);
	if(!sock)
	{
		SDLNet_Quit();
		return 0;
	}

	log_message(DEBUG,"sending login info: %s\n", message.sender);
	log_message(DEBUG," -- %d, %s \n", sock, message.tail);
	/*
	 * send client data
	 */
	if (!rocsmq_send(sock,&message, 0)) {
		return 0;
	}

	log_message(DEBUG, "successfully logged in");
	return sock;
}
OSErr NetRegisterName(const unsigned char *name, const unsigned char *type, short version, short socketNumber,
					  const char* hint_addr_string)
{
//    fdprintf("NetRegisterName %d, %d\n", version, socketNumber);

	OSErr theError = noErr;

    // Construct a service-instance for the player
    struct SSLP_ServiceInstance	thePlayer;

    NetLookup_BuildTypeString(thePlayer.sslps_type, type, version);

    // Truncate and copy Pstring name; add a terminating null for C-friendliness.
    unsigned char theLength = name[0];
    if(theLength > SSLP_MAX_NAME_LENGTH - 2)
        theLength = SSLP_MAX_NAME_LENGTH - 2;
    
    thePlayer.sslps_name[0] = theLength;
    memcpy(&thePlayer.sslps_name[1], &name[1], theLength);
    thePlayer.sslps_name[theLength + 1] = '\0';

    thePlayer.sslps_address.host = 0;
    thePlayer.sslps_address.port = socketNumber;
    
    // Publish it
    SSLP_Allow_Service_Discovery(&thePlayer);
    
    sNameRegistered = true;

	// If we're supposed to hint, resolve the address string and start hinting.
	if(hint_addr_string != NULL) {
		IPaddress	theAddress;

		// SDL_net declares ResolveAddress without "const" on the char; we can't guarantee
		// our caller that it will remain const unless we protect it like this.
		char*		theStringCopy = strdup(hint_addr_string);

		theError = SDLNet_ResolveHost(&theAddress, theStringCopy, 0);
		if(theError == 0) {
			SSLP_Hint_Service_Discovery(&thePlayer, &theAddress);
		}

		free(theStringCopy);
	}
    
    return theError;
}
static void NET_SDL_SendPacket(net_addr_t *addr, net_packet_t *packet)
{
    UDPpacket sdl_packet;
    IPaddress ip;
   
    if (addr == &net_broadcast_addr)
    {
        SDLNet_ResolveHost(&ip, NULL, port);
        ip.host = INADDR_BROADCAST;
    }
    else
    {
        ip = *((IPaddress *) addr->handle);
    }

#if 0
    {
        static int this_second_sent = 0;
        static int lasttime;

        this_second_sent += packet->len + 64;

        if (I_GetTime() - lasttime > TICRATE)
        {
            printf("%i bytes sent in the last second\n", this_second_sent);
            lasttime = I_GetTime();
            this_second_sent = 0;
        }
    }
#endif

#ifdef DROP_PACKETS
    if ((rand() % 4) == 0)
        return;
#endif

    sdl_packet.channel = 0;
    sdl_packet.data = packet->data;
    sdl_packet.len = packet->len;
    sdl_packet.address = ip;

    if (!SDLNet_UDP_Send(udpsocket, -1, &sdl_packet))
    {
        I_Error("NET_SDL_SendPacket: Error transmitting packet: %s",
                SDLNet_GetError());
    }
}
Exemple #18
0
bool FTP_Socket::onEnter()
{
    std::cout << "FTP_Socket::onEnter()" << std::endl;
    IPaddress ip;

    set = SDLNet_AllocSocketSet(1);
    if(!set)
    {
        printf("SDLNet_AllocSocketSet: %s\n", SDLNet_GetError());
        onExit();
        return false;
    }

    /* Resolve the argument into an IP address type */
    std::cout << "Connecting to " << host.c_str() << " on port " << port << std::endl;
    if(SDLNet_ResolveHost(&ip,host.c_str(),port) == -1)
    {
        printf("SDLNet_ResolveHost: %s\n",SDLNet_GetError());
        onExit();
        return false;
    }

    //open the socket
    controlSocket = SDLNet_TCP_Open(&ip);
    if(!controlSocket)
    {
        printf("SDLNet_TCP_Open: %s\n",SDLNet_GetError());
        onExit();
        return false;
    }

    if(SDLNet_TCP_AddSocket(set,controlSocket) == -1)
    {
        printf("SDLNet_TCP_AddSocket: %s\n",SDLNet_GetError());
        onExit();
        return false;
    }

    /* reference Only
    if(SDLNet_TCP_DelSocket(set,controlSocket) == -1)
    {
        printf("SDLNet_DelSocket: %s\n",SDLNet_GetError());
        onExit();
        return false;
    } */
    return true;
}
Exemple #19
0
/* Resolve a host name and port to an IP address in network form */
int SDLNet_ResolveHost(IPaddress *address, const char *host, Uint16 port)
{
	int retval = 0;

	/* Perform the actual host resolution */
	if ( host == NULL ) {
		address->host = INADDR_ANY;
	} else {
/*		int a[4];

		address->host = INADDR_NONE;
		
		if ( sscanf(host, "%d.%d.%d.%d", a, a+1, a+2, a+3) == 4 ) {
			if ( !(a[0] & 0xFFFFFF00) && !(a[1] & 0xFFFFFF00) &&
			     !(a[2] & 0xFFFFFF00) && !(a[3] & 0xFFFFFF00) ) {
				address->host = ((a[0] << 24) |
				                 (a[1] << 16) |
				                 (a[2] <<  8) | a[3]);
				if ( address->host == 0x7F000001 ) {
					address->host = OTlocalhost;
				}
			}
		}
		
		if ( address->host == INADDR_NONE ) {*/
			InetHostInfo hinfo;
			
			/* Check for special case - localhost */
			if ( strcmp(host, "localhost") == 0 )
				return(SDLNet_ResolveHost(address, "127.0.0.1", port));

			/* Have OpenTransport resolve the hostname for us */
			retval = OTInetStringToAddress(dnsStatus.dns, (char *)host, &hinfo);
			if (retval == noErr) {
				while( dnsStatus.stat != dnsResolved )
					{WaitNextEvent(everyEvent, 0, 1, NULL );}
				address->host = hinfo.addrs[0];
			}
		//}
	}
	
	address->port = SDL_SwapBE16(port);

	/* Return the status */
	return(retval);
}
Exemple #20
0
bool init() {
    if (SDL_Init(SDL_INIT_VIDEO)<0) { printf("SDL init failure.\n"); return false;}
    if (SDLNet_Init()<0) printf("SDL net init failure.\n");
    int initFlags = IMG_INIT_PNG;
    if (!(IMG_Init(initFlags) & initFlags)) { printf("IMG init failure.\n"); return false;}
    if (!loadMedia()) { printf("Couldn't load meida.\n"); return false;}
    udpSendSock = SDLNet_UDP_Open(0);
    udpRecvSock = SDLNet_UDP_Open(0);
    if (udpSendSock == NULL || udpRecvSock == NULL) { printf("Couldn't open UDP sockets.\n"); return false;}
    IPaddress serverIP;
    SDLNet_ResolveHost(&serverIP, NULL, 4444);
    TCPsock = SDLNet_TCP_Open(&serverIP);
    if (TCPsock==NULL) { printf("Couldn't open TCP socket.\n"); return false;}
    packetOut = SDLNet_AllocPacket(1024);
    //packetOut->data=gameData;
    return true;
}
Exemple #21
0
Server::Server(int port)
	:mxClients(SDL_CreateMutex()),
	myMapManager(MapManager::getInstance()),
	exit_request(false),
	chat_mode(false),
	mxGoSerial(SDL_CreateMutex()),
	myIdServer(new IDServer(this)),
	initialized(false),
	myGamefsm(this),
	myConsole(this)
{
	/*
	 * Fills the IPaddress object with correct data to create
	 * a valid TCP listening socket for the server.
	 */
	if(SDLNet_ResolveHost(&(this->data->address),NULL,port)==-1)
	{
		std::cerr << "SDLNet_ResolveHost: " << SDLNet_GetError() << std::endl;
		SDLNet_Quit();
		SDL_Quit();
		exit(3);
	}

	/*
	 * Creates the server's socket that will accept new connections.
	 */
	this->data->socket = SDLNet_TCP_Open(&(this->data->address));
	if(!(this->data->socket)){
		std::cerr << "SDserverDLNet_TCP_Open: " << SDLNet_GetError() << std::endl;
		exit(4);
	}

	this->data->running = true; // The server is running ...
	this->data->self = this;	// Pointer to self.
	this->data->id= 0;			// For the moment we set this to 0.

	/*
	 * Creates a new thread for the server socket.
	 */
	 this->data->thread = SDL_CreateThread(startThread, this->data);
	 if (this->data->thread == NULL) {
	 	std::cerr << "SDL_CreateThread: " << SDL_GetError() << std::endl;
        exit(5);
    }
}
TCP_NetClient::TCP_NetClient(const char hostname[], ushort port) : TCP_NetBase()
{
	IPaddress addr;
	SDLNet_ResolveHost(&addr, hostname, port); //TODO NET change from local host to real session later
	mySocket = SDLNet_TCP_Open(&addr);
	if (mySocket == NULL) {
		NETMSG("Failed to initialize TCP client socket");
		setErrorFlag();
		return;
	}

	recvThread = SDL_CreateThread(reinterpret_cast<int (*)(void *)>(recvThreadFunc), this);
	if (recvThread == NULL) {
		NETMSG("Failed to initialize TCP client receive thread");
		setErrorFlag();
		return;
	}
}
Exemple #23
0
int network_send_score (char* initials, long score)
{
	IPaddress ip;		/* Server address */
	TCPsocket sd;		/* Socket descriptor */
	int len = (sizeof (char) * 3) + sizeof (long)   ;
	char buffer[len];

	if (SDLNet_Init() < 0)
	{
		fprintf(stderr, "SDLNet_Init: %s\n", SDLNet_GetError());
		return (EXIT_FAILURE);
	}

	/* Resolve the host we are connecting to */
	if (SDLNet_ResolveHost(&ip, HOST, PORT) < 0)
	{
		fprintf(stderr, "SDLNet_ResolveHost: %s\n", SDLNet_GetError());
		return (EXIT_FAILURE);
	}

	/* Open a connection with the IP provided (listen on the host's port) */
	if (!(sd = SDLNet_TCP_Open(&ip)))
	{
		fprintf(stderr, "SDLNet_TCP_Open: %s\n", SDLNet_GetError());
		return (EXIT_FAILURE);
	}

	/* Build and send message */
    memset (buffer, 0, sizeof(len));
    memcpy (buffer, initials, 3);
    memcpy (buffer+3, &score, sizeof(score));

    if (SDLNet_TCP_Send(sd, (void *)buffer, len) < len)
    {
        fprintf (stderr, "SDLNet_TCP_Send: %s\n", SDLNet_GetError());
        return (EXIT_FAILURE);
    }

	SDLNet_TCP_Close(sd);
	SDLNet_Quit();

	return 0;
}
Exemple #24
0
	void NetworkThread::initNetwork() {
		std::cout << "<<<<<<<<<<<<< NetworkThread::initNetwork()" << std::endl;;
		if (SDLNet_Init() < 0) {
			std::cout << "<<<<<<<<<<<<< SDLNet_Init: " << SDLNet_GetError() << std::endl;;
			exit(EXIT_FAILURE);
		}
	 
		/* Resolving the host using NULL make network interface to listen */
		if (SDLNet_ResolveHost(&ip, NULL, port)) {
			std::cout << "<<<<<<<<<<<<< SDLNet_ResolveHost: " << SDLNet_GetError() << std::endl;
			exit(EXIT_FAILURE);
		}
	 
		/* Open a connection with the IP provided (listen on the host's port) */
		if (!(sd = SDLNet_TCP_Open(&ip))) {
			std::cout << "<<<<<<<<<<<<< SDLNet_TCP_Open: " << SDLNet_GetError() << std::endl;
			exit(EXIT_FAILURE);
		}
	}
Exemple #25
0
void client_engine::join(char * ipaddr, char * port)
{
  IPaddress ip;
 
  if ( SDLNet_ResolveHost(&ip, ipaddr, atoi(port) ) )
  {
    cerr<<"could not resolve host: "<<SDLNet_GetError()<<endl;
    exit(1);
  }

  _host = SDLNet_TCP_Open(&ip);
  if ( ! _host )
  {
    cerr<<"Could not connect to host..."<<SDLNet_GetError()<<endl;
    exit(1);
  }

  _host_set = SDLNet_AllocSocketSet(1);
  if ( ! _host_set )
  {
    cerr<<"Could not allocate socket set "<<SDLNet_GetError()<<endl;
    exit(1);
  }

  SDLNet_TCP_AddSocket(_host_set, _host);

  _to_host = new message_handler(_host, MAX_MESSAGES);
  assert(_to_host);

  // get the number of the local player
  int rec;
  char line[MAX_LEN];
  rec = SDLNet_TCP_Recv(_host, line, MAX_LEN-1);

  if ( rec > 0 )
  {
    line[rec] = '\0';
    istringstream id(line);

    id>>line; // should say YOUARENUMBER
    id>>_local_player;
    cout<<"got "<<line<<_local_player<<endl;
  }
Exemple #26
0
void CServer::OpenServer()
{

    if (SDLNet_ResolveHost (&addr, NULL, 6699) < 0)
    {
        printf ("ERR ResolveHost: %s\n", SDLNet_GetError ());
        SDLNet_Quit ();
        exit (-1);
    }

    server = SDLNet_TCP_Open (&addr);

    if (server == NULL)
    {
        printf ("ERR TCP_Open: %s\n", SDLNet_GetError ());
        SDLNet_Quit ();
        exit (-1);
    }

    client = SDLNet_TCP_Accept (server);
    cout << "Server wurde Gestartet !" << endl;
    int x = 0;
    while (client == NULL)
    {
        x++;
        SDL_Delay (1000);
        client = SDLNet_TCP_Accept (server);
        if (x == 10)
        {
            pMenu->start = false;
            pMenu->bServer = false;
            pFramework->done = true;
            SAFE_DELETE (remoteIP);
            SDLNet_TCP_Close(server);
            SDLNet_Quit();
            cout << "Server wurde Beendet !" << endl;
            return;
        }

    }
    cout << "Client hat verbunden !" << endl;
}
Exemple #27
0
TCPServerSocket::TCPServerSocket(Bit16u port)
{
	isopen = false;
	mysock = 0;
	if(!SDLNetInited) {
        if(SDLNet_Init()==-1) {
			LOG_MSG("SDLNet_Init failed: %s\n", SDLNet_GetError());
			return;
		}
		SDLNetInited = true;
	}
	if (port) {
		IPaddress listen_ip;
		SDLNet_ResolveHost(&listen_ip, NULL, port);
		mysock=SDLNet_TCP_Open(&listen_ip);
		if(!mysock) return;
	}
	else return;
	isopen = true;
}
TCPsocket connect() {
	IPaddress ip;
	TCPsocket socket;
	int port = 0;
	printf("Enter port to listen to: ");
	scanf("%d", &port);

	if (SDLNet_ResolveHost(&ip, NULL, port) == -1) {
		printf("SDLNet_ResolveHost: %s\n", SDLNet_GetError());
		exit(1);
	}
	ip.host = INADDR_ANY;

	socket = SDLNet_TCP_Open(&ip);
	if (!socket) {
		printf("SDLNet_TCP_Open: %s\n", SDLNet_GetError());
		exit(2);
	}
	return socket;
}
Exemple #29
0
void
ngl_net_open(void)
{
	if (SDLNet_Init()<0) {
		fprintf(stderr, "SDLNet_Init: %s\n", SDLNet_GetError());
		exit(EXIT_FAILURE);
	}
 
	/* Resolving the host using NULL make network interface to listen */
	if (SDLNet_ResolveHost(&ip, NULL, localport)<0) {
		fprintf(stderr, "SDLNet_ResolveHost: %s\n", SDLNet_GetError());
		exit(EXIT_FAILURE);
	}
 
	/* Open a connection with the IP provided (listen on the host's port) */
	if (!(sd = SDLNet_TCP_Open(&ip))) {
		fprintf(stderr, "SDLNet_TCP_Open: %s\n", SDLNet_GetError());
		exit(EXIT_FAILURE);
	}
}
Exemple #30
0
std::tuple<int, int> Peer::GetRemotePeer(const std::string address) const {
	Print("resolving host (getremotepeer string)... '%s'\n", address);
	IPaddress IP;
	int dns;
	int count = 0;
	do
	{
		dns = SDLNet_ResolveHost(&IP,address.c_str(),0);
		if (!dns)
		{
			Print("found dns match: %i\n", getIP(IP.host));
			return GetRemotePeer(&IP);
		}
		count++;
	} while (count < 100 && !dns);

	if (!dns) Print("DNS Failed, tried: %i\n", count);
	
	return std::make_tuple(-1,-1);
}