SHARE
TWEET

Untitled

a guest Feb 19th, 2019 63 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <unistd.h>
  4. #include <string.h>
  5. #include <sys/types.h>
  6. #include <sys/socket.h>
  7. #include <netinet/in.h>
  8. #include <netdb.h>
  9. #include <iostream>
  10.  
  11. using namespace std;
  12.  
  13. const int BUFFER_SIZE = 1024;
  14. int sockfd;
  15. struct sockaddr_in serv_addr;
  16. struct hostent *server;
  17.  
  18. int main(int argc, char* argv[]) {
  19.     //Create and check socket
  20.     sockfd = socket(AF_INET, SOCK_STREAM, 0);
  21.     if (sockfd < 0) {
  22.         fprintf(stderr,"ERROR opening socket\n");
  23.         exit(0);
  24.     }
  25.    
  26.     //Setting up sockaddr
  27.     server = gethostbyname("127.0.0.1");
  28.     if (server == NULL) {
  29.         fprintf(stderr,"ERROR: no such host\n");
  30.         exit(0);
  31.     }
  32.     bzero((char *) &serv_addr, sizeof(serv_addr));
  33.     serv_addr.sin_family = AF_INET;                     //Set adress family
  34.     serv_addr.sin_port = htons(8000);                   //Convert and set port
  35.     bcopy((char *)server->h_addr, (char *)&serv_addr.sin_addr.s_addr, server->h_length);    //Connect to self
  36.    
  37.     //Trying to connect
  38.     if (connect(sockfd, (struct sockaddr *)&serv_addr, sizeof(serv_addr)) < 0) {
  39.         fprintf(stderr, "ERROR connecting\n");
  40.         exit(0);
  41.     }
  42.    
  43.     char buffer[BUFFER_SIZE];    //Buffer
  44.     int n;
  45.     bzero(buffer, BUFFER_SIZE);    //Fill buffer with zeros
  46.  
  47.     fprintf(stdout, "Введите фразу для поиска: ");
  48.     fgets(buffer, BUFFER_SIZE, stdin);
  49.     n = write(sockfd, buffer, strlen(buffer));    
  50.    
  51.     //Check written
  52.     if (n < 0) {
  53.         fprintf(stderr, "ERROR writing to socket");
  54.         exit(0);
  55.     }
  56.  
  57.     //Check read
  58.     bzero(buffer, BUFFER_SIZE);
  59.     n = read(sockfd, buffer, BUFFER_SIZE);
  60.     if (n < 0) {
  61.         fprintf(stderr, "ERROR reading from socket");
  62.         exit(0);
  63.     }
  64.     printf("%s\n", buffer);
  65.     close(sockfd);
  66. }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
Not a member of Pastebin yet?
Sign Up, it unlocks many cool features!
 
Top