UDP

Download as pdf or txt
Download as pdf or txt
You are on page 1of 3

UDP SERVER

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/socket.h>
#include <arpa/inet.h>

#define LEN 100


#define PORT 10000
#define SA struct sockaddr

int main() {
char buff[LEN];
struct sockaddr_in serv, cli;
int sockfd, clen = sizeof(cli), slen = sizeof(serv);

printf("\n------------SERVER------------\n");

if ((sockfd = socket(AF_INET, SOCK_DGRAM, 0)) == -1) {


printf("\nSocket creation failed\n");
exit(1);
}
printf("\nSocket created\n");

bzero(&serv, sizeof(serv));
serv.sin_family = AF_INET;
serv.sin_addr.s_addr = htonl(INADDR_ANY);
serv.sin_port = htons(PORT);

if (bind(sockfd, (SA*)&serv, sizeof(serv)) == -1) {


printf("\nBinding failed\n");
exit(1);
}
printf("\nBinding successful\n");

while (1) {
int n=0;
bzero(buff, LEN);

if (recvfrom(sockfd, buff, LEN, 0, (SA*)&cli, &clen) == -1) {


printf("\nFailed to receive\n");
continue;
}
printf("\nMessage: %s\n", buff);

printf("Enter message to client: ");


while ((buff[n++] = getchar()) != '\n');

if (sendto(sockfd, buff, strlen(buff) + 1, 0, (SA*)&cli, clen) == -1) {


printf("\nFailed to send message\n");
} else {
printf("\nMessage sent to client\n");
}
}

close(sockfd);
return 0;
}

UDP CLIENT
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/socket.h>
#include <arpa/inet.h>

#define LEN 100


#define PORT 10000
#define SA struct sockaddr

int main() {
char buff[LEN];
struct sockaddr_in serv;
int sockfd, slen = sizeof(serv);

printf("\n------------CLIENT------------\n");

if ((sockfd = socket(AF_INET, SOCK_DGRAM, 0)) == -1) {


printf("\nSocket creation failed\n");
exit(1);
}
printf("\nSocket created\n");

bzero(&serv, sizeof(serv));
serv.sin_family = AF_INET;
serv.sin_addr.s_addr = inet_addr("127.0.0.1");
serv.sin_port = htons(PORT);

while (1) {
int n=0;
printf("Enter message to server: ");
while ((buff[n++] = getchar()) != '\n');
if (strcmp(buff, "exit") == 0) {
break;
}

if (sendto(sockfd, buff, strlen(buff) + 1, 0, (SA*)&serv, slen) == -1) {


printf("\nFailed to send\n");
exit(1);
}
printf("\nMessage sent to server\n");

bzero(buff, LEN);

if (recvfrom(sockfd, buff, LEN, 0, (SA*)&serv, &slen) == -1) {


printf("\nFailed to receive\n");
exit(1);
}
printf("Message from server: %s\n", buff);
}

close(sockfd);
return 0;
}

You might also like