Simon
Simon

Reputation: 241

What is the following format specifier doing?

         else
        {
            printf("\\%.3hho", *data);
        }

I could not find information regarding on how to decipher it on the net or by reading the C programming language book. I saw it in the following code snippet. The code is trying to perform password sniffing in the telnet protocol.

if ((pktlen - sizeof(struct ipheader)) >  dataoffset)
{
    printf("   SrcIP: %s,", inet_ntoa(ip->iph_sourceip));
    printf(" DstIP: %s,", inet_ntoa(ip->iph_destip));
    printf(" Data: ");
    u_char* data = (u_char*)tcp + dataoffset;

    for (unsigned short s = 0; s < (ntohs(ip->iph_len) - (sizeof(struct ipheader) + dataoffset)); s++)
    {
        if (isprint(*data) != 0)
        {
          printf("%c", *data);
                                  }
        else
        {
            printf("\\%.3hho", *data);
        }
        data++;
    }
    printf("\n");
  }

}

Upvotes: 2

Views: 72

Answers (2)

iBug
iBug

Reputation: 37317

According to CppReference:

Conversion specifier o

converts a unsigned integer into octal representation oooo,

Precision specifies the minimum number of digits to appear. <truncated>

So the string \\%.3hho represents a literal backslash (it's escaped), plus the format specifier %.3hho:

  • %...o indicates octal representation for unsigned integer. The letter o also indicates the end of this specifier
  • hh is a C99 specification, indicates unsigned char instead of unsigned int, always a single byte
  • .3 means the precision is 3, so at least 3 octal digits (000 - 377)

Upvotes: 1

dbush
dbush

Reputation: 225767

The %o format specifier prints an unsigned value in octal. The hh length modifier tells it that the value is a char, and the .3 precision means that at least 3 characters will be printed.

Upvotes: 1

Related Questions