-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Add a quick conversion of ip -> int & int -> ip.
Functionalities should be more helpful for the Python 2 users, since the Python 3 is more useful to use ipaddress lib
- Loading branch information
Showing
2 changed files
with
38 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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)) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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" | ||
) |