Skip to content

Commit

Permalink
Add a quick conversion of ip -> int & int -> ip.
Browse files Browse the repository at this point in the history
Functionalities should be more helpful for the Python 2 users, since the Python 3 is more useful to use ipaddress lib
  • Loading branch information
NexSabre committed Feb 15, 2021
1 parent 6e257ac commit b53bd35
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 0 deletions.
15 changes: 15 additions & 0 deletions scapy_helper/helpers/ip.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
import socket
import struct


def ip2int(ip_address):
if not isinstance(ip_address, str):
raise TypeError("Value %s is not a type of string" % ip_address)
return struct.unpack("!I", socket.inet_aton(ip_address))[0]


def int2ip(integer):
if type(integer).__name__ not in ("int", "long"):
# hack: since in the python3, long is not supported
raise TypeError("Value %s is not a number" % integer)
return socket.inet_ntoa(struct.pack("!I", integer))
23 changes: 23 additions & 0 deletions test/helpers/test_ip.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
from unittest import TestCase

from scapy_helper.helpers.ip import int2ip, ip2int


class TestIP(TestCase):
def setUp(self):
self.integer = 3232235521
self.ip = "192.168.0.1"

def test_ip2int(self):
self.assertEqual(
ip2int(self.ip),
self.integer,
"Values should be equal"
)

def test_int2ip(self):
self.assertEqual(
int2ip(self.integer),
self.ip,
"Values should be equal"
)

0 comments on commit b53bd35

Please sign in to comment.