Advertisement
Guest User

Untitled

a guest
Apr 20th, 2019
100
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.14 KB | None | 0 0
  1. #include <stdlib.h>
  2. #include <unistd.h>
  3. #include <errno.h>
  4. #include <string.h>
  5. #include <netdb.h>
  6. #include <sys/types.h>
  7. #include <netinet/in.h>
  8. #include <sys/socket.h>
  9.  
  10. #define MAXDATASIZE 1024 //število prebranih zlogov
  11.  
  12. int main(int argc, char *argv[]) {
  13.  
  14. int sockfd, numbytes; // socekt file descriptor, new file descriptor
  15. char buf[MAXDATASIZE]; // array holding the string to be received via TCP
  16. struct hostent *he; // pointer to the structure hostent (returned by gethostbyname)
  17. struct sockaddr_in their_addr; // server address
  18.  
  19. if (argc != 3) {
  20. write(0,"Uporaba: TCPtimec ime vrata\n\0", 29);
  21. exit(1);
  22. }
  23.  
  24. // get the server IP address
  25. if ((he = gethostbyname(argv[1])) == NULL) {
  26. herror("gethostbyname"); // prints string + value of h_error variable [HOST_NOT_FOUND || NO_ADDRESS or NO_DATA || NO_RECOVERY || TRY_AGAIN]
  27. exit(1);
  28. }
  29.  
  30. // create socket
  31. if ((sockfd = socket(PF_INET, SOCK_STREAM, 0)) == -1) {
  32. perror("socket");
  33. exit(1);
  34. }
  35.  
  36. their_addr.sin_family = AF_INET; // family to Address Family InterNET
  37. their_addr.sin_port = htons(atoi(argv[2])); // get server's port number - should be checked for input errors (not a number, etc.)
  38. their_addr.sin_addr = *((struct in_addr *)he->h_addr); // server's IP address from hostent structure pointed to by he variable...
  39. memset(&(their_addr.sin_zero), '\0', 8); // for conversion between structures only, a trick to ensure pointer casting...
  40.  
  41.  
  42. // connect to the server... (no bind necessary as we are connecting to remote host... Kernel will find a free port for us and will bind it to sockfd)
  43. if (connect(sockfd, (struct sockaddr *)&their_addr, sizeof(struct sockaddr)) == -1) {
  44. perror("connect");
  45. exit(1);
  46. }
  47.  
  48. // as long there is soething to read...
  49. while(numbytes != 0) {
  50.  
  51. // receive numbytes from server...
  52. if ((numbytes = recv(sockfd, buf, MAXDATASIZE-1, 0)) == -1) {
  53. perror("recv");
  54. exit(1);
  55. }
  56.  
  57. buf[numbytes] = '\0'; // all strings in c ends with \0 (see strlen)
  58.  
  59. // print received string to standard output
  60. write(0, buf, numbytes);
  61. }
  62.  
  63. // close socket
  64. close(sockfd);
  65.  
  66. return 0;
  67. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement