Using client-side sockets in datagram mode

In C language:

After creating the socket, you will have to send a first datagram to the server via the sendto function which requires 6 parameters:

We will therefore have to declare a variant of the sockaddr structure corresponding to AF_INET. This is the struct sockaddr_in type. We will start by zeroing the content of this structure via the bzero function of string.h, then we will assign, to the first field, named here sin_family, the AF_INET value.

struct sockaddr_in	addr;

bzero(&addr, sizeof(addr));
addr.sin_family = AF_INET;
	

You must then fill in the structure, the sin_addr field with the IPv4 address of the server to contact and the sin_port field with the number of its UDP port.

Notes:

inet_aton("127.0.0.1", &addr.sin_addr);
addr.sin_port = htons(7);
	

Having thus specified the address 127.0.0.1 and the port 7, all that remains is to call the sendto function so that the client tries to establish the connection with the local echo server.

sendto(fd, &buffer, sizeof(buffer), MSG_CONFIRM, (struct sockaddr *) &addr, sizeof(addr));
	

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 and strlen
#include <arpa/inet.h>	// for the function inet_addr

int main()
{
	int fd;
	struct sockaddr_in addr;
	int err;
	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");
	return 0;
}
	

PHP and Python:

In languages like PHP or Python, there are libraries interfacing with system functions.

PHP

The example code written in C becomes in PHP:

$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
if ($socket == false) die("Socket creation error!\n");
$buffer = "Hello !";
$len = strlen($buffer);
socket_sendto($socket, $buffer, $len, '127.0.0.1', 8080);
echo "Message sent to server!\n";
	

Python

The example code written in C becomes in Python:

try :
	sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
	sock.sendto("Hello !",('127.0.0.1',8080))
except socket.error :
	print("Customer communication error!")
	exit()
print("Message sent to server!")