-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathipv4mutate.py
More file actions
68 lines (55 loc) · 2.1 KB
/
ipv4mutate.py
File metadata and controls
68 lines (55 loc) · 2.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
import ipaddress
from random import randint
from typing import List
class IPv4Mutate:
"""Mutates IPv4 addresses provided in dotted-decimal notation."""
def __init__(self, iparg: str) -> None:
# Validate and store the provided IP as an IPv4Address object
self._ip_obj = ipaddress.IPv4Address(iparg)
self._ip_str = iparg
@property
def mutate_binary(self) -> str:
"""Each octet as its 8-bit binary representation."""
return ".".join(f"{int(x):08b}" for x in self._ip_str.split("."))
@property
def mutate_dotted_hex(self) -> str:
"""Each octet as its hexadecimal representation."""
return ".".join(hex(int(x)) for x in self._ip_str.split("."))
@property
def mutate_hex(self) -> str:
"""The full IP as a single hexadecimal string."""
return f"0x{int(self._ip_obj):08x}"
@property
def mutate_octal(self) -> str:
"""Each octet as its octal representation (leading 0o removed)."""
return ".".join(oct(int(x)).replace("0o", "0") for x in self._ip_str.split("."))
@property
def mutate_octal_padded(self) -> str:
"""Each octet as octal with random leading zero padding."""
octets = [oct(int(x)).replace("0o", "0") for x in self._ip_str.split(".")]
return ".".join(f"{'0' * randint(1, 20)}{o}" for o in octets)
@property
def mutate_zero_padded(self) -> str:
"""Dotted-decimal with octets left-padded with zeros, to 3 digits."""
return ".".join(x.zfill(3) for x in self._ip_str.split("."))
@property
def mutate_decimal(self) -> int:
"""The integer representation of the IP."""
return int(self._ip_obj)
@property
def mutate_zero_stripped(self) -> str:
"""Strips middle octets if they are zero (0). This may change the provided IP,
such as:
- provided 127.0.5.7
- this creates 127.5.7
- expands back to 127.5.0.7, NOT the same IP as provided"""
parts = self._ip_str.split(".")
return ".".join([x for x in parts if x != "0"])
@property
def mutate_urlencoded(self) -> str:
"""URL-encoded representation of the IP string."""
return "".join(f"%{ord(c):02x}" for c in self._ip_str)
def __repr__(self) -> str:
return self._ip_str
def __str__(self) -> str:
return self._ip_str