Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

printf() - prints wrong order. Works when printed separately

Tags:

c

printf

I'm trying to print some text in common log format.

printf("%s - - [%s] %s %d %zu\n", ip, _time, row, statuscode, size);

The problem is that the order gets all mixed up. The output is:

200 1511 - - [20/Sep/2017:13:07:32 +0200] GET / HTTP/1.1

I think (1511) is the ip getting printed. Don't know why.

When I print them like this:

printf("1. %s\n", ip);
printf("2. %s\n", _time);
printf("3. %s\n", row);
printf("4. %d\n", statuscode);
printf("5. %zu\n", size);

It works like expected:

1. 127.0.0.1
2. 20/Sep/2017:13:11:24 +0200
3. GET / HTTP/1.1
4. 200
5. 151

It seems the problem starts when i add statuscode for some reason. I have no clue why. Any help is appreciated.

Here is the function where I use prinft():

static void handlelogging(char* method, struct sockaddr_storage client_addr, size_t size, char* row, int statuscode) {

char* ip;
char _time[80];
struct tm *info;
time_t rawtime;

time(&rawtime);
info = localtime(&rawtime);
strftime(_time, 80,"%d/%b/%Y:%H:%M:%S %z", info)
ip = getip(client_addr);

//Print goes here, see above.
}

As someone said it could be a problem with the ip variable:

static char* getip(struct sockaddr_storage client_addr) {
    char ipstr[20];
    struct sockaddr_in *s;


    s = (struct sockaddr_in *) &client_addr;

    /**
     * Converts network address (s) in the IPV_4 family into a string.
     */
    return strdup(inet_ntop(AF_INET, &s->sin_addr, ipstr, sizeof ipstr));
 }
like image 529
gel Avatar asked Mar 08 '23 00:03

gel


1 Answers

I think that the problem comes from row which contains a \r character.

Just modify it with strchr(...)

/* replace all '\r' by 'R' in row */
char *p = strchr(row, '\r');
while(p)
{ 
    *p = 'R';
    p = strchr(row, '\r');
}
like image 161
Mathieu Avatar answered Mar 23 '23 23:03

Mathieu