Dialogue continued

After the first datagram transfer from the customer to the server, the server having identified the customer's IP address and UDP port, it will be able to respond to it via the sendto function while the customer will use the recvfrom function to wait for the response datagram from the server.

Client side example

#include <stdio.h>
#include <stdlib.h>

#include <sys/types.h>
#include <netdb.h>
#include <sys/socket.h>

#include <string.h>		// for the functions bzero et strlen
#include <arpa/inet.h>	// for the function inet_addr

int main()
{
	int fd;
	struct sockaddr_in addr;
	int err, addr_len, n;
	char buffer[]="Hello !";

	fd = socket (AF_INET, SOCK_DGRAM, IPPROTO_UDP);
	if (fd<0) {
		printf("Socket creation error!\n");
		exit(1);
	}

	bzero(&addr, sizeof(addr));
	addr.sin_family = AF_INET;
	err = inet_aton("127.0.0.1", &addr.sin_addr);
	if (err == 0) {
		printf("Invalid IPv4 address!\n");
		exit(1);
	}
	addr.sin_port = htons(8080);

	sendto(fd, &buffer, strlen(buffer), MSG_CONFIRM, (struct sockaddr *) &addr, sizeof(addr)); 
	printf("Message sent to server !\n");

	addr_len = sizeof(addr);
	n = recvfrom(fd, &buffer, sizeof(buffer), 0, (struct sockaddr *) &addr, &addr_len);
	printf("message of size %d bytes received from %s:%d\n", n, inet_ntoa(addr.sin_addr), ntohs(addr.sin_port));
	return 0;
}
	

Server side example

#include <stdio.h>
#include <stdlib.h>

#include <sys/types.h>
#include <netdb.h>
#include <sys/socket.h>

#include <string.h>		// for the functions bzero et strlen
#include <arpa/inet.h>	// for the function inet_addr

int main()
{
	int fd_srv;
	struct sockaddr_in adr_srv, adr_cli;
	socklen_t adr_cli_len;
	int err;

	int n;
	char buffer[1024];

	fd_srv = socket (AF_INET, SOCK_DGRAM, IPPROTO_UDP);
	if (fd_srv<0) {
		printf("Socket creation error!\n");
		exit(1);
	}

	bzero(&adr_srv, sizeof(adr_srv));
	adr_srv.sin_family = AF_INET;
	err = inet_aton("127.0.0.1", &adr_srv.sin_addr);
	if (err == 0) {
		printf("Adresse IPv4 invalide!\n");
		exit(1);
	}
	addr.sin_port = htons(8080);
	err = bind(fd_srv, (struct sockaddr *) &adr_srv, sizeof(adr_srv));
	if (err != 0) {
		printf("Server port access error !\n");
		exit(1);
	}

	while(1) {
		adr_cli_len = sizeof(adr_cli);
		n = recvfrom(fd_srv, &buffer, sizeof(buffer), MSG_WAITALL, (struct sockaddr *) &adr_cli, &adr_cli_len);
		printf("Message of size %d bytes received from %s:%d\n", n, inet_ntoa(adr_cli.sin_addr), ntohs(adr_cli.sin_port));

		sendto(fd_srv, &buffer, strlen(buffer), 0, (struct sockaddr *) &adr_cli, adr_cli_len);
		printf("Answer sent to client!\n");
	}
	return 0;
}