Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //Server
- #include <stdio.h>
- #include <string.h>
- #include <sys/socket.h>
- #include <arpa/inet.h>
- int main(void){
- int sockfd;
- struct sockaddr_in server_addr, client_addr;
- char server_message[2000], client_message[2000];
- int clientlen = sizeof(client_addr);
- memset(server_message, '\0', sizeof(server_message));
- memset(client_message, '\0', sizeof(client_message));
- sockfd = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
- if(sockfd < 0)
- {
- printf("Error while creating socket\n");
- return -1;
- }
- else
- {
- printf("Socket created successfully\n");
- }
- server_addr.sin_family = AF_INET;
- server_addr.sin_port = htons(7000);
- server_addr.sin_addr.s_addr = inet_addr("127.0.0.1");
- if(bind(sockfd, (struct sockaddr*)&server_addr, sizeof(server_addr)) < 0)
- {
- printf("Couldn't bind to the port\n");
- return -1;
- }
- else
- {
- printf("Done with binding\n");
- printf("Listening for incoming messages...\n\n");
- }
- if (recvfrom(sockfd, client_message, sizeof(client_message), 0,
- (struct sockaddr*)&client_addr, &clientlen) < 0)
- {
- printf("Couldn't receive\n");
- return -1;
- }
- else
- {
- printf("Received message from IP: %s and port: %i\n",
- inet_ntoa(client_addr.sin_addr), ntohs(client_addr.sin_port));
- printf("Msg from client: %s\n", client_message);
- printf("Enter Response\n");
- gets(server_message);
- }
- if (sendto(sockfd, server_message, strlen(server_message), 0,
- (struct sockaddr*)&client_addr, clientlen) < 0)
- {
- printf("Can't send\n");
- return -1;
- }
- close(sockfd);
- return 0;
- }
- //Client
- #include <stdio.h>
- #include <string.h>
- #include <sys/socket.h>
- #include <arpa/inet.h>
- int main(void){
- int sockfd;
- struct sockaddr_in server_addr;
- char server_message[2000], client_message[2000];
- int serverlen = sizeof(server_addr);
- memset(server_message, '\0', sizeof(server_message));
- memset(client_message, '\0', sizeof(client_message));
- sockfd = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
- if(sockfd < 0)
- {
- printf("Error while creating socket\n");
- return -1;
- }
- else
- {
- printf("Socket created successfully\n");
- server_addr.sin_family = AF_INET;
- server_addr.sin_port = htons(7000);
- server_addr.sin_addr.s_addr = inet_addr("127.0.0.1");
- printf("Enter message: ");
- gets(client_message);
- }
- if(sendto(sockfd, client_message, strlen(client_message), 0,
- (struct sockaddr*)&server_addr, serverlen) < 0){
- printf("Unable to send message\n");
- return -1;
- }
- if(recvfrom(sockfd, server_message, sizeof(server_message), 0,
- (struct sockaddr*)&server_addr, &serverlen) < 0)
- {
- printf("Error while receiving server's msg\n");
- return -1;
- }
- else
- {
- printf("Server's response: %s\n", server_message);
- close(sockfd);
- }
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement