#include <stdio.h>
#include <string.h>
#include <sys/types.h>
#include <sys/time.h>
#include <unistd.h>
#include "i_net.h"


#define mst_server 100
#define mst_end    101

int       msg;
netadr_t  masteraddr; // address of the master server
char      masterip[] = "csdoom.dhs.org";
//char      masterip[] = "127.0.0.1";
buf_t   message;
byte    message_buffer[MAX_UDP_PACKET];

int main()
{
	localport = LAUNCHERPORT;
	InitNetCommon();

        message.data = message_buffer;
	message.maxsize = sizeof(message_buffer);

	Printf ("Quering the Master Server...\n");
	
	NET_StringToAdr (masterip, &masteraddr);
	I_SetPort(masteraddr, MASTERPORT);
	
	SZ_Clear(&message);
	MSG_WriteLong(&message, LAUNCHER_CHALLENGE);
	NET_SendPacket(message.cursize, message.data, masteraddr);
	
	int numtry = 5;
	
	while (numtry--)
	{
	    I_DoSelect();	
		
	    if (NET_GetPacket() )
	    {
	        int challenge = MSG_ReadLong();
		
		if (challenge != LAUNCHER_CHALLENGE)
		    return 0;
		    
	    	while ( (msg = MSG_ReadByte() ) != mst_end)
		   Printf ("Server IP = %s\n", MSG_ReadString() );

		return 0;
	    }
	}	
	
	Printf ("Can't connect.\n");
	
	return 0;
}