#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netdb.h>
#include <netinet/in.h>

struct hostent * h;
struct sockaddr_in as,ac;

int main (int args, char* argv[]){
	
	int lgaddr = sizeof(struct sockaddr_in);
	h = gethostbyname(argv[1]); //--> adress magine = ip
	if (h == NULL){
		printf("gethostbyname marche pas\n");
		exit(5);
	}
	short int serv = htons(atoi(argv[2]));// htons = host to network short (integer) / -->port (ou service)


	// A décrire:
	//as.sin_addr
	//as.sin_port
	//as.sin_family

	memcpy(&as.sin_addr, h->h_addr, 4); // on met les 4 premiers octets de 2e arg dans 1e arg
	as.sin_port = serv;	
	as.sin_family = AF_INET;//-->"c'est de l'internet"

	//on ouvre une porte vers l'extérieur en UDP
	int theConnection = socket(AF_INET, SOCK_DGRAM, 0);// SOCK_DGRAM : pour dire qu'on fait de l'UDP
	//socket renvoie le numéro du fichier de connection (-1 si ça marche pas)
	if(theConnection < 0){
		printf("socket ne marche pas\n");
		exit(5);
	}
	int rc = bind(theConnection, (struct sockaddr*)&as, lgaddr); //affecte un numéro à theConnection
	// 0=O probleme, -1=probleme!
	if(rc<0){
		printf("bind ne marche pas\n");
		exit(5);
	}
	
	while(1){
		char theMsg[100] = "Hello!";
		int la;

		int theConversation = sendto(theConnection, theMsg, strlen(theMsg), 0, (struct sockaddr*)&as, lgaddr);//bloquant tant qu'il n'a rien a lire
		printf("theConversation de sendto: %d\n",theConversation);

		char theMg[100]="";
		theConversation = recvfrom(theConnection, theMg, sizeof(theMg), 0, (struct sockaddr*)&ac, &la);
		printf("theConversation de recvfrom: %d\n",theConversation);
		printf("Message reçu: %s\n",theMg);
		printf("la: %d\n",la);
		break;

		close(theConversation);
	}
return 1;

}
