Computer Networks UDP Program Tips
Computer Networks UDP Program Tips
https://rtpnotes.vercel.app
https://pgmsite.netlify.app
Computer-Networks-UDP-Program-Tips
UDP-Client
Include Statements
UDP-Client: Basic Algorithm for remembering
UDP-Client: Steps in more detail
1. Create the socket
2. Setup Server address struct
3. Loop
3.1 Read input and send message to server
3.2 Receive message from server and display message
#include <stdio.h>
#include <string.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
3. Loop
sendto sends data to a server using the previously created UDP socket
sendto has the following parameters
lfd : This is the file descriptor of the socke
Buffer
Length of Buffer
Flags
Set as 0
(struct sockaddr *)&server : This argument specifies the address of the server
you want to send data to. It's a pointer to a struct sockaddr which is a generic
socket address structure.
n
size of server struct
Parameters used
First 5 parameters are similar
&n : This is a pointer to an integer variable.
The recvfrom function will store the number of bytes actually received from the
server in this memory location pointed to by &n . This allows you to know how
much data you received successfully.
close(lfd);
Bind
The bind function is used to associate a socket with a specific local IP address and port
number.
The parameters used are
sockfd
The file descriptor of the socket to be bound. In your example, this is lfd ,
which is the listening file descriptor.
addr (const struct sockaddr *):
A pointer to a struct sockaddr that contains the address to bind to the socket.
addrlen (socklen_t):
The size of the address structure. In your example, this is sizeof(server) ,
which is the size of the struct sockaddr_in structure.
4. Loop
The recvfrom function will store the number of bytes actually received from the
server in this memory location pointed to by &n . This allows you to know how
much data you received successfully.\
sendto sends data to a server using the previously created UDP socket
sendto has the following parameters
lfd : This is the file descriptor of the socke
Buffer
Length of Buffer
Flags
Set as 0
(struct sockaddr *)&server : This argument specifies the address of the server
you want to send data to. It's a pointer to a struct sockaddr which is a generic
socket address structure.
n
size of server struct