Aim :Write a program for client server using point to point connection.
Client
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netdb.h>
/* the port users will be connecting to */
#define MYPORT 8888
int main(int argc, char *argv[ ])
{
int sockfd;
/* connector’s address information */
struct sockaddr_in their_addr;
struct hostent *he;
int numbytes;
/*i get the host info */
he = gethostbyname(argv[1]);
sockfd = socket(AF_INET, SOCK_DGRAM, 0);
/* host byte order */
their_addr.sin_family = AF_INET;
/* short, network byte order */
printf("Using port: 8888\n");
their_addr.sin_port = htons(MYPORT);
their_addr.sin_addr = *((struct in_addr *)he->h_addr);
/* zero the rest of the struct */
memset(&(their_addr.sin_zero), '\0', 8);
numbytes = sendto(sockfd, argv[2], strlen(argv[2]), 0, (struct sockaddr *)&their_addr, sizeof(struct sockaddr));
if (close(sockfd) != 0)
printf("Your Messege is not sent...sorry\n");
else
printf("Your Messege is successfully sent.\n");
return 0;
}
Server
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#define MYPORT 8888
#define MAXBUFLEN 500
int main(int argc, char *argv[])
{
int sockfd;
/* my address information */
struct sockaddr_in my_addr;
/* connector’s address information */
struct sockaddr_in their_addr;
int addr_len, numbytes;
char buf[MAXBUFLEN];
sockfd = socket(AF_INET, SOCK_DGRAM, 0);
printf("Server-socket() sockfd is OK...\n");
/* host byte order */
my_addr.sin_family = AF_INET;
/* short, network byte order */
my_addr.sin_port = htons(MYPORT);
/* automatically fill with my IP */
my_addr.sin_addr.s_addr = INADDR_ANY;
/* zero the rest of the struct */
memset(&(my_addr.sin_zero), '\0', 8);
bind(sockfd, (struct sockaddr *)&my_addr, sizeof(struct sockaddr));
addr_len = sizeof(struct sockaddr);
numbytes = recvfrom(sockfd, buf, MAXBUFLEN-1, 0, (struct sockaddr *)&their_addr, &addr_len);
buf[numbytes] = '\0';
printf("THIS MSG SEND BY CLIENT TO SERVER ::> \"%s\"\n", buf);
close(sockfd);
return 0;
}
No comments:
Post a Comment