Skip to content

Instantly share code, notes, and snippets.

@vaimalaviya1233
Forked from Endermanch/swag.py
Created August 29, 2025 05:58
Show Gist options
  • Save vaimalaviya1233/701e0fccaf1f1c03439ffafdce9eaa6e to your computer and use it in GitHub Desktop.
Save vaimalaviya1233/701e0fccaf1f1c03439ffafdce9eaa6e to your computer and use it in GitHub Desktop.
Swag and unswag your IP address
def swag(ip: str) -> int:
parts = ip.strip().split('.')
if len(parts) != 4:
raise ValueError("Invalid IPv4 address: must have 4 octets")
total = 0
for i, p in enumerate(parts):
if not p.isdigit():
raise ValueError(f"Octet {i + 1} is not a number")
n = int(p)
if not (0 <= n <= 255):
raise ValueError(f"Octet {i + 1} out of range (0-255)")
total = (total << 8) | n
if (total >> 24) == 0:
raise ValueError("First octet cannot be 0")
return total
def unswag(num: int) -> str:
if not (0x01000000 <= num <= 0xFFFFFFFF):
raise ValueError("Number out of IPv4 range (16777216–4294967295)")
octets = []
for shift in (24, 16, 8, 0):
octets.append(str((num >> shift) & 0xFF))
return ".".join(octets)
def main():
print("1. IP to Decimal")
print("2. Decimal to IP")
try:
mode = int(input("Enter mode (1 or 2): ").strip())
if mode == 1:
ip = input("Enter IPv4 address: ").strip()
print(swag(ip))
elif mode == 2:
num = int(input("Enter decimal number: ").strip())
print(unswag(num))
else:
print("Invalid mode. Please enter 1 or 2.")
except Exception as e:
print(f"Error: {e}")
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment