Expt 8
Expt 8
UDP:
Source Code
Server Code
The server initializes a UDP socket, receives messages from a client, and sends a
response back.
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
int main() {
int sockfd;
char buffer[MAXLINE];
exit(EXIT_FAILURE);
memset(&servaddr, 0, sizeof(servaddr));
memset(&cliaddr, 0, sizeof(cliaddr));
servaddr.sin_addr.s_addr = INADDR_ANY;
servaddr.sin_port = htons(PORT);
perror("bind failed");
exit(EXIT_FAILURE);
int len, n;
len = sizeof(cliaddr);
buffer[n] = '\0';
return 0;
Client Code
The client initializes a UDP socket, sends a message to the server, and waits for a
response.
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
int main() {
int sockfd;
char buffer[MAXLINE];
exit(EXIT_FAILURE);
memset(&servaddr, 0, sizeof(servaddr));
servaddr.sin_family = AF_INET;
servaddr.sin_port = htons(PORT);
servaddr.sin_addr.s_addr = INADDR_ANY;
int n, len;
buffer[n] = '\0';
close(sockfd);
return 0;
}
Explanation
1. Server:
o Waits for a message from the client and responds with "Hello from server."
2. Client:
o Creates a UDP socket and sends "Hello from client" to the server.
Output Example
Server
$ ./server
Client
$ ./client