From 9ca0b3f7ecfcda303a08537ae546771e58d18877 Mon Sep 17 00:00:00 2001
From: Pierre LALET <pierre.lalet@cea.fr>
Date: Thu, 19 Jan 2017 19:48:11 +0100
Subject: [PATCH] Fix SourceIPField() + add a couple of tests

---
 scapy/fields.py     | 29 ++++++++++++++---------------
 test/regression.uts | 14 ++++++++++++++
 2 files changed, 28 insertions(+), 15 deletions(-)

diff --git a/scapy/fields.py b/scapy/fields.py
index ffd0209d..cbe15534 100644
--- a/scapy/fields.py
+++ b/scapy/fields.py
@@ -257,26 +257,25 @@ class SourceIPField(IPField):
     def __init__(self, name, dstname):
         IPField.__init__(self, name, None)
         self.dstname = dstname
+    def __findaddr(self, pkt):
+        if conf.route is None:
+            # unused import, only to initialize conf.route
+            import scapy.route
+        dst = ("0.0.0.0" if self.dstname is None
+               else getattr(pkt, self.dstname))
+        if isinstance(dst, (Gen, list)):
+            r = {conf.route.route(daddr) for daddr in dst}
+            if len(r) > 1:
+                warning("More than one possible route for %r" % (dst,))
+            return min(r)[1]
+        return conf.route.route(dst)[1]
     def i2m(self, pkt, x):
         if x is None:
-            iff,x,gw = pkt.route()
-            if x is None:
-                x = "0.0.0.0"
+            x = self.__findaddr(pkt)
         return IPField.i2m(self, pkt, x)
     def i2h(self, pkt, x):
         if x is None:
-            if conf.route is None:
-                # unused import, only to initialize conf.route
-                import scapy.route
-            dst = ("0.0.0.0" if self.dstname is None else
-                   getattr(pkt, self.dstname))
-            if isinstance(dst, (Gen, list)):
-                r = {conf.route.route(daddr) for daddr in dst}
-                if len(r) > 1:
-                    warning("More than one possible route for %r" % (dst,))
-                x = min(r)[1]
-            else:
-                x = conf.route.route(dst)[1]
+            x = self.__findaddr(pkt)
         return IPField.i2h(self, pkt, x)
 
     
diff --git a/test/regression.uts b/test/regression.uts
index 25c7ec5f..f8bec41e 100644
--- a/test/regression.uts
+++ b/test/regression.uts
@@ -279,6 +279,20 @@ assert( _ == ("ABCD","1.2.3.4") )
 i.addfield(None, "FOO", "1.2.3.4")
 assert( _ == "FOO\x01\x02\x03\x04" )
 
+= SourceIPField
+~ core field
+defgw = conf.route.route('0.0.0.0')[1]
+class Test(Packet): fields_desc = [SourceIPField("sourceip", None)]
+
+assert Test().sourceip == defgw
+assert Test(str(Test())).sourceip == defgw
+
+assert IP(dst="0.0.0.0").src == defgw
+assert IP(str(IP(dst="0.0.0.0"))).src == defgw
+assert IP(dst="0.0.0.0/31").src == defgw
+assert IP(str(IP(dst="0.0.0.0/31"))).src == defgw
+
+
 #= ByteField
 #~ core field
 #b = ByteField("foo", None)
-- 
GitLab