Advertisement
Raviqa

sisiClient.c

Apr 7th, 2020
328
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 2.22 KB | None | 0 0
  1. // Nama : Raviqa Sandra Putri
  2. // Nim  : 1856401009
  3.  
  4. #include <sys/types.h>
  5. #include <sys/socket.h>
  6. #include <netdb.h>
  7. #include <string.h>
  8. #include <stdio.h>
  9. #include <stdlib.h>
  10. #include <unistd.h>
  11. #include <netinet/in.h>
  12. #include <arpa/inet.h>
  13.  
  14. #define MAXBUF 1024
  15.  
  16. int main(int argc, char* argv[]){
  17.     int udpSocket;
  18.     int returnStatus, returnStatus1;
  19.     int addrlen;
  20.     struct sockaddr_in udpClient, udpServer;
  21.     char buf[MAXBUF];
  22.     char buf1[MAXBUF];
  23.  
  24.     if(argc < 5){
  25.         fprintf(stderr, "Usage: %s <ip address> <port> <username> <password>\n", argv[0]);
  26.         exit(1);
  27.     }
  28.  
  29.     udpSocket = socket(AF_INET, SOCK_DGRAM, 0);
  30.  
  31.     if(udpSocket == -1){
  32.         fprintf(stderr, "Could not create a scoket!\n");
  33.         exit(1);
  34.     } else {
  35.         printf("Socket created.\n");
  36.     }
  37.  
  38.     udpClient.sin_family = AF_INET;
  39.     udpClient.sin_addr.s_addr = INADDR_ANY;
  40.     udpClient.sin_port =  0;
  41.  
  42.     returnStatus = bind(udpSocket, (struct sockaddr*)&udpClient, sizeof(udpClient));
  43.  
  44.     if(returnStatus == 0 ){
  45.         fprintf(stderr, "Bind Completed!\n");
  46.     } else {
  47.         fprintf(stderr, "Could not bind to address!\n");
  48.         close(udpSocket);
  49.         exit(1);
  50.     }
  51.     udpServer.sin_family = AF_INET;
  52.     udpServer.sin_addr.s_addr = inet_addr(argv[1]);
  53.     udpServer.sin_port = htons(atoi(argv[2]));
  54.     strcpy(buf, argv[3]);
  55.     returnStatus = sendto(udpSocket, buf, strlen(buf)+1, 0, (struct sockaddr*)&udpServer, sizeof(udpServer));
  56.     strcpy(buf1, argv[4]);
  57.     returnStatus = sendto(udpSocket, buf1, strlen(buf)+1, 0, (struct sockaddr*)&udpServer, sizeof(udpServer));
  58.  
  59.     if(returnStatus == -1 && returnStatus == -1){
  60.         fprintf(stderr, "Could not send message!\n");
  61.     } else {
  62.         printf("Message sent.\n");
  63.         /*message sent look for confirmation*/
  64.         addrlen = sizeof(udpServer);
  65.         returnStatus = recvfrom(udpSocket, buf, MAXBUF, 0, (struct sockaddr*)&udpServer, &addrlen);
  66.         if (returnStatus == -1){
  67.             fprintf(stderr, "Did not Receive confirmation!\n");
  68.         }
  69.         else {
  70.             buf[returnStatus] = 0;
  71.             printf("received: %s\n",buf);
  72.         }
  73.     }
  74.     close(udpSocket);
  75.     return 0;
  76. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement