Advertisement
Guest User

client.c

a guest
Sep 21st, 2016
129
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.91 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <string.h>
  3. #include <stdlib.h>
  4. #include <unistd.h>
  5. #include <sys/socket.h>
  6. #include <netinet/in.h>
  7. #include <netdb.h>
  8.  
  9. #define DATA "Hello Server!"
  10.  
  11. int main(int argc, char *argv[]) {
  12. int c_socket;
  13. char buffer[1024];
  14. struct sockaddr_in s_addr;
  15. socklen_t addr_size;
  16. struct hostent *hostname;
  17.  
  18. /*---- Checking input ----*/
  19. if ( argc != 2 ) {
  20. printf("Usage: %s $hostname\n", argv[0]);
  21. exit(1);
  22. }
  23.  
  24. /*---- Create the socket. The three arguments are: ----*/
  25. /* 1) Internet domain 2) Stream socket 3) Default protocol (TCP in this case) */
  26. c_socket = socket(AF_INET, SOCK_STREAM, 0);
  27.  
  28.  
  29. /*---- Configure settings of the server address struct ----*/
  30. s_addr.sin_family = AF_INET;
  31. s_addr.sin_port = htons(5001);
  32.  
  33. hostname = gethostbyname(argv[1]);
  34. if ( hostname == NULL ) {
  35. printf("Can't resolve hostname '%s'\n", argv[1]);
  36. exit(1);
  37. }
  38.  
  39. memset(s_addr.sin_zero, '\0', sizeof s_addr.sin_zero);
  40.  
  41.  
  42. /*---- Connect the socket to the server using the address struct ----*/
  43. addr_size = sizeof s_addr;
  44. if ( connect(c_socket, (struct sockaddr *) &s_addr, addr_size) < 0 ) {
  45. printf("Connection to server can't be established\n");
  46. exit(1);
  47. }
  48.  
  49.  
  50. /*---- Read the message from the server into the buffer ----*/
  51. if (recv(c_socket, buffer, sizeof(buffer), 0) < 0) {
  52. printf("Can't get message from server\n");
  53. exit(1);
  54. }
  55. else {
  56. printf("Message received from server: %s\n", buffer);
  57. }
  58.  
  59. strcpy(buffer, DATA);
  60. if ( send(c_socket, buffer, sizeof(buffer), 0) < 0) {
  61. printf("Can't send a message\n");
  62. close(c_socket);
  63. exit(1);
  64. }
  65. else {
  66. printf("Message sent: %s\n", buffer);
  67. }
  68.  
  69. close(c_socket);
  70.  
  71. return 0;
  72. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement