-4

I want to read the file and match 2 words first i connect with a socket get the input write it to a file then i wanna read that file and get the match of 2 words and do something afterword but seems like it doesn't work So here is the code

#include<stdio.h>
#include<string.h>    //strlen
#include<sys/socket.h>
#include<arpa/inet.h> //inet_addr

int main(int argc , char *argv[])
{
    int socket_desc;
    struct sockaddr_in server;
    char *message, server_reply [2000];
    FILE *f; 
    //Create socket
    socket_desc = socket(AF_INET , SOCK_STREAM , 0);
    if (socket_desc == -1)
    {
        printf("Could not create socket");
    }

    server.sin_addr.s_addr = inet_addr("86.127.118.157");
    server.sin_family = AF_INET;
    server.sin_port = htons( 80 );

    //Connect to remote server
    if (connect(socket_desc , (struct sockaddr *)&server , sizeof(server)) < 0)
    {
        puts("connect error");
        return 1;
    }

    puts("Connected\n");

    //Send some data
    message = "GET / HTTP/1.1\r\n\r\n";
    if( send(socket_desc , message , strlen(message) , 0) < 0)
    {
        puts("Send failed");
        return 1;
    }
    puts("Data Send\n");

//Receive a reply from the server
    if( recv(socket_desc, server_reply , 2000 , 0) < 0)
    {
        puts("recv failed");
    }
    puts("Reply received\n");
    puts(server_reply);
    // Open and write the file
    f = fopen("date.txt", "w");   
    fprintf(f, server_reply);
     // read and match the words
    while (fgets (server_reply, 2500, f)) {
    if( strcmp(server_reply, "258"))
    {
    fputs(server_reply, f);
        }else{
    puts("I could not loccate the bug");
    }
    // file close
    fclose(f);
    return 0;
}
}
Cœur
  • 37,241
  • 25
  • 195
  • 267
f00
  • 1
  • 1

1 Answers1

1

The problem is that you are assuming that you read strings from the socket. That is wrong. You read bytes. There's no implicit zero terminator, you have to do all that yourself.

Save the return value of recv(2) - that will tell you how many bytes you read.

Read in a loop - recv(2) will return as soon as some data is available (or the other end closed the connection, or error happened), so you might need to stitch a message together between the reads.

Nikolai Fetissov
  • 82,306
  • 11
  • 110
  • 171
  • this is what i received. **Reply received HT�** – f00 Aug 18 '15 at 18:36
  • Exactly - see that non-printable character there? This means you are touching memory beyond the bytes read from the socket. This is the receipt for disaster (a crash at best). – Nikolai Fetissov Aug 18 '15 at 18:53
  • and wats really happening its ? :) – f00 Aug 19 '15 at 18:01
  • What's really happening is you expect somebody else to fix your code. That's not what we do here. Read up on socket programming, figure it out, ask intelligent questions. You can start here http://beej.us/guide/bgnet/output/html/singlepage/bgnet.html – Nikolai Fetissov Aug 19 '15 at 18:35