I’m trying to convert this Python code to C. But for the life of me, I can’t figure out what this line here does. The rest of the program seems simple.
self.payload = "\x02\x00%s%s" % (
pack(">b", length),
"".join(random.choice(string.printable) for i in range(length)))
If anybody could give me a rough idea of what this is doing, it’d be much appreciated!
First line:
length = random.randint(18, 20)isint length = rand() % 3 + 18.Now let’s dissect the dense second line piece by piece.
"\x02\x00%s%s" % (x, y)means to substitute the format string with the given arguments (likesprintf()). In this case it means concatenating the bytes 0x02, 0x00 with two stringsxandyto follow.x = pack(">b", length)usesstruct.pack(). In this case, it means to convert the integer valuelengthinto one byte representing its value. It’s almost equivalent to usingchr().y = "".join(z)means to take each element in the listz(which must be a string) and concatenate them with “” (nothing) between them. (For example,"@".join(["a","b","c"]) --> "a@b@c".)z = (random.choice(string.printable) for i in range(length))returns a generator object. You can think of it as a list whose elements are computed on demand. In this case, it generateslengthelements where each element is one character randomly chosen from the stringstring.printable.All in all, the second line yields a string that starts wxth 0x02 0x00, followed by
(char)length, followed bylengthrandom characters each uniformly chosen from the set of charsstring.printable.