sprintf(format, [relax=1]) -> str Where format is a string that can include directives. A directive begins and ends by % and has the following format: ``%[fmt[r],][cls[:nb].]field%`` :param fmt: is a classic printf directive, "r" can be appended for raw
(self, fmt, relax=1)
| 1551 | return self.__class__(raw(self)).show(dump, indent, lvl, label_lvl) |
| 1552 | |
| 1553 | def sprintf(self, fmt, relax=1): |
| 1554 | # type: (str, int) -> str |
| 1555 | """ |
| 1556 | sprintf(format, [relax=1]) -> str |
| 1557 | |
| 1558 | Where format is a string that can include directives. A directive |
| 1559 | begins and ends by % and has the following format: |
| 1560 | ``%[fmt[r],][cls[:nb].]field%`` |
| 1561 | |
| 1562 | :param fmt: is a classic printf directive, "r" can be appended for raw |
| 1563 | substitution: |
| 1564 | (ex: IP.flags=0x18 instead of SA), nb is the number of the layer |
| 1565 | (ex: for IP/IP packets, IP:2.src is the src of the upper IP layer). |
| 1566 | Special case : "%.time%" is the creation time. |
| 1567 | Ex:: |
| 1568 | |
| 1569 | p.sprintf( |
| 1570 | "%.time% %-15s,IP.src% -> %-15s,IP.dst% %IP.chksum% " |
| 1571 | "%03xr,IP.proto% %r,TCP.flags%" |
| 1572 | ) |
| 1573 | |
| 1574 | Moreover, the format string can include conditional statements. A |
| 1575 | conditional statement looks like : {layer:string} where layer is a |
| 1576 | layer name, and string is the string to insert in place of the |
| 1577 | condition if it is true, i.e. if layer is present. If layer is |
| 1578 | preceded by a "!", the result is inverted. Conditions can be |
| 1579 | imbricated. A valid statement can be:: |
| 1580 | |
| 1581 | p.sprintf("This is a{TCP: TCP}{UDP: UDP}{ICMP:n ICMP} packet") |
| 1582 | p.sprintf("{IP:%IP.dst% {ICMP:%ICMP.type%}{TCP:%TCP.dport%}}") |
| 1583 | |
| 1584 | A side effect is that, to obtain "{" and "}" characters, you must use |
| 1585 | "%(" and "%)". |
| 1586 | """ |
| 1587 | |
| 1588 | escape = {"%": "%", |
| 1589 | "(": "{", |
| 1590 | ")": "}"} |
| 1591 | |
| 1592 | # Evaluate conditions |
| 1593 | while "{" in fmt: |
| 1594 | i = fmt.rindex("{") |
| 1595 | j = fmt[i + 1:].index("}") |
| 1596 | cond = fmt[i + 1:i + j + 1] |
| 1597 | k = cond.find(":") |
| 1598 | if k < 0: |
| 1599 | raise Scapy_Exception("Bad condition in format string: [%s] (read sprintf doc!)" % cond) # noqa: E501 |
| 1600 | cond, format_ = cond[:k], cond[k + 1:] |
| 1601 | res = False |
| 1602 | if cond[0] == "!": |
| 1603 | res = True |
| 1604 | cond = cond[1:] |
| 1605 | if self.haslayer(cond): |
| 1606 | res = not res |
| 1607 | if not res: |
| 1608 | format_ = "" |
| 1609 | fmt = fmt[:i] + format_ + fmt[i + j + 2:] |
| 1610 |
no test coverage detected