Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //Server:-
- #include <sys/socket.h>
- #include <sys/types.h>
- #include <netinet/in.h>
- #include <arpa/inet.h>
- #include <string.h>
- #include <stdio.h>
- #include <stdlib.h>
- #include <unistd.h>
- #include <netdb.h>
- #define MAX 100
- int main()
- {
- int sockfd,stat;
- struct sockaddr_in serveraddr;
- struct sockaddr_in clientaddr;
- char buf[MAX];
- socklen_t clientlen;
- sockfd = socket(AF_INET,SOCK_DGRAM,0);
- if(sockfd==-1)
- {
- printf("Error Connecting socket\n");
- exit(0);
- }
- else
- {
- printf("Socket is created\n");
- serveraddr.sin_family=AF_INET;
- serveraddr.sin_port=htons(7000);
- serveraddr.sin_addr.s_addr=inet_addr("127.0.0.1");
- stat=bind(sockfd,(struct sockaddr *)&serveraddr,sizeof(serveraddr));
- }
- if(stat==-1)
- {
- printf("Error assigning socket\n");
- exit(0);
- }
- else
- {
- printf("Socket assigned\n");
- }
- memset(buf,0,MAX);
- clientlen=sizeof(serveraddr);
- while(1)
- {
- memset(buf,0,MAX);
- recvfrom(sockfd,buf,MAX,0,(struct sockaddr *)&clientaddr,&clientlen);
- printf("Data from port number:\t");
- printf("%d\n",htons(clientaddr.sin_port));
- printf("Message from client:\t");
- printf("%s\n",buf);
- memset(buf,0,MAX);
- }
- close(sockfd);
- return 0;
- }
- //Client:-
- #include <sys/socket.h>
- #include <sys/types.h>
- #include <netinet/in.h>
- #include <arpa/inet.h>
- #include <string.h>
- #include <stdio.h>
- #include <stdlib.h>
- #include <unistd.h>
- #include <netdb.h>
- #define MAX 100
- int main()
- {
- int sockfd,stat;
- struct sockaddr_in serveraddr;
- struct sockaddr_in clientaddr;
- char buf[MAX];
- socklen_t serverlen;
- sockfd = socket(AF_INET,SOCK_DGRAM,0);
- if(sockfd==-1)
- {
- printf("Error Connecting socket\n");
- exit(0);
- }
- else
- {
- printf("Socket is created\n");
- clientaddr.sin_family=AF_INET;
- clientaddr.sin_port=htons(0);
- clientaddr.sin_addr.s_addr=inet_addr("127.0.0.1");
- stat=bind(sockfd,(struct sockaddr *)&clientaddr,sizeof(clientaddr));
- }
- if(stat==-1)
- {
- printf("Error assigning client socket\n");
- exit(0);
- }
- else
- {
- printf("Socket assigned");
- serveraddr.sin_family=AF_INET;
- serveraddr.sin_port=htons(7000);
- serveraddr.sin_addr.s_addr=inet_addr("127.0.0.1");
- memset(buf,0,MAX);
- printf("Enter the data\n");
- printf("'.' on nextline ends the socket\n");
- while(1)
- {
- memset(buf,0,MAX);
- scanf("\t%s",buf);
- if(strcmp(buf,".")==0)
- {
- break;
- }
- sendto(sockfd,buf,MAX,0,(struct sockaddr *)&serveraddr,sizeof(serveraddr));
- memset(buf,0,MAX);
- }
- close(sockfd);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement