First of all let us take a look at UDP. It is necessary to create a socket. This socket can later be used to send or receive a UDP message.
Example 1.1. Create a UDP socket
#include<string.h>
#include<sys/socket.h>
#include<netinet/in.h>
int create_udp_socket(int port) {
/*socketdescriptor*/
int s;
/*struct used for binding the socket to a local address*/
struct sockaddr_in host_address;
/*create the socket*/
s=socket(PF_INET, SOCK_DGRAM, IPPROTO_UDP);
if (s < 0) { /*errorhandling ....*/}
/*init the host_address the socket is beeing bound to*/
memset((void*)&host_address, 0, sizeof(host_address));
/*set address family*/
host_address.sin_family=PF_INET;
/*accept any incoming messages:*/
host_address.sin_addr.s_addr=INADDR_ANY;
/*the port the socket i to be bound to:*/
host_address.sin_port=htons(port);
/*bind it...*/
if (
bind(s, (struct sockaddr*)&host_address, sizeof(host_address)) < 0
) {
/*errorhandling...*/
}
return s;
}
Example 1.2. Use a UDP socket to send a message
#define BUF_SIZE 1000
#define LOCAL_PORT 5000
#define REMOTE_PORT 5000
...
int s; /*the socket descriptor*/
char buffer[BUF_SIZE]; /*the message to send*/
struct sockaddr_in target_host_address; /*the receiver's address*/
unsigned char* target_address_holder; /*a pointer to the ip address*/
...
/*create the socket*/
s = create_udp_socket(LOCAL_PORT);
if (s == -1) {errorhandling.....}
/*init target address structure*/
target_host_address.sin_family=PF_INET;
target_host_address.sin_port=htons(REMOTE_PORT);
target_address_holder=(unsigned char*)&target_host_address.sin_addr.s_addr;
target_address_holder[0]=10;
target_address_holder[1]=0;
target_address_holder[2]=0;
target_address_holder[3]=1;
/*fill message with random data....*/
for (j = 0; j < BUF_SIZE; j++) {
buffer[j] = (unsigned char)((int) (255.0*rand()/(RAND_MAX+1.0)));
}
/*send it*/
sendto(s, buffer, BUF_SIZE, 0,
(struct sockaddr*)&target_host_address, sizeof(struct sockaddr));
Example 1.3. Use a UDP socket to receive a message
#define BUF_SIZE 1000
#define LOCAL_PORT 5000
...
char buffer[BUF_SIZE];
/*address of the sender will be stored here*/
struct sockaddr_in host_address;
int hst_addr_size = sizeof(host_address);
/*length of the incoming packet*/
int length = 0;
/*socketdescriptor*/
int s;
...
/*create the socket*/
s = create_udp_socket(LOCAL_PORT);
if (s == -1) {errorhandling.....}
/*wait for incoming message*/
length = recvfrom(s, buffer, BUF_SIZE, 0,
(struct sockaddr*)&host_address, &hst_addr_size);