GURU
GURU

Reputation: 575

How do I read only the second line from this char buffer in c?

  char buf[256];
    ssize_t bytes_read; 
    /* Read some data from the client.  */
    bytes_read = read (fd, buf, sizeof (buf) - 1);
    buf[bytes_read] = '\0';
    printf ("Buffer %s", buf);

This is the output display.

GET /index.html HTTP/1.1

Host: 127.0.0.1:8080

User-Agent: Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:33.0) Gecko/20100101 Firefox/33.0

Accept: text/html,application/xhtml+xml,application/xml;q=0.9,/;q=0.8

Accept-Language: en-US,en;q=0.5

Accept-EncoMy hostname: ubuntu FILE : 58HTTP/1.1 200 OK

Date: Tue, 03 Mar 2015 15:56:02

Server: Host server

Last-Modified: Tue, 17 Feb 2015 00:19:56

Content-type: text/html

Content-length: 58

I only need to store the "127.0.0.1". Please kindly advise. Thank you.

Upvotes: 0

Views: 241

Answers (1)

Heinrich du Toit
Heinrich du Toit

Reputation: 458

Reference for c string handling library: link

What you seem to want to do is commonly called "splitting the string". In your case by line so you will split at line end characters. Note depending on your input this might be "\n" or "\r\n"

The function you need is strtok The link includes a very nice example on how to split a string.

You just need to split by "\n" for example:

    char *token = strtok(input, "\n");
    while(token) {
        printf(token);
        token = strtok(NULL, "\n");
    }

Rather than printf you can now save your lines one by one for later use or you can keep a counter and just process the second line and then exit if that is all you need.

Upvotes: 1

Related Questions