Guest User

Untitled

a guest
May 26th, 2018
84
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.40 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <string.h>
  4. #include <sys/types.h>
  5. #include <sys/socket.h>
  6. #include <arpa/inet.h>
  7.  
  8.  
  9. int main(int argc, char *argv[])
  10. {
  11. if (argc < 3)
  12. { // using command line argument
  13. printf("Usage: %s <serv_ip> <serv_port>\n", argv[0]);
  14. exit(1);
  15. }
  16.  
  17. int cfd, serv_port;
  18. serv_port = strtoul(argv[2], NULL, 10);//string to unsigned long
  19.  
  20. /*
  21. Create your Socket do error checking
  22. Remember socket returns a socket descriptor
  23. SOCK_STREAM --->TCP
  24. or
  25. SOCK_DGRAM --->UDP
  26. AF_INET ------->protocol/address family
  27.  
  28.  
  29. if ((cfd = socket(AF_INET, SOCK_STREAM, 0)) < 0)
  30. {
  31. perror("socket");
  32. exit(2);
  33. }
  34.  
  35. struct sockaddr_in saddr = {0};
  36. saddr.sin_family = AF_INET; // set to AF_INET
  37. saddr.sin_port = htons(serv_port); // Port number
  38. saddr.sin_addr.s_addr = inet_addr(argv[1]); // IP address eg "192.168.1.1"
  39.  
  40. /*
  41. 1. Connect to the server using proper API for connect
  42. 2. Send data to connected server
  43. 3. Receive data from connected server and print data received
  44. 4. Close the connection
  45. */
  46.  
  47. if (connect(cfd, (struct sockaddr *)&saddr, sizeof(saddr)) < 0)
  48. {
  49. perror("connect");
  50. close(cfd);
  51. exit(3);
  52. }
  53.  
  54. if (send(cfd, "Hello", strlen("Hello"), 0) < 0)
  55. {
  56. perror("send");
  57. close(cfd);
  58. exit(4);
  59. }
  60.  
  61. char buf[20] = {0};
  62. if (recv(cfd, buf, sizeof(buf), 0) < 0)
  63. {
  64. perror("recv");
  65. close(cfd);
  66. exit(5);
  67. }
  68.  
  69. printf("Data received: %s\n", buf);
  70.  
  71. close(cfd); */
  72.  
  73. return 0;
  74. }
Add Comment
Please, Sign In to add comment