MCPcopy Create free account
hub / github.com/secdev/scapy / getmacbyip

Function getmacbyip

scapy/layers/l2.py:138–193  ·  view source on GitHub ↗

Returns the destination MAC address used to reach a given IP address. This will follow the routing table and will issue an ARP request if necessary. Special cases (multicast, etc.) are also handled. .. seealso:: :func:`~scapy.layers.inet6.getmacbyip6` for IPv6.

(ip, chainCC=0)

Source from the content-addressed store, hash-verified

136
137@conf.commands.register
138def getmacbyip(ip, chainCC=0):
139 # type: (str, int) -> Optional[str]
140 """
141 Returns the destination MAC address used to reach a given IP address.
142
143 This will follow the routing table and will issue an ARP request if
144 necessary. Special cases (multicast, etc.) are also handled.
145
146 .. seealso:: :func:`~scapy.layers.inet6.getmacbyip6` for IPv6.
147 """
148 # Sanitize the IP
149 if isinstance(ip, Net):
150 ip = next(iter(ip))
151 ip = inet_ntoa(inet_aton(ip or "0.0.0.0"))
152
153 # Multicast
154 if in4_ismaddr(ip): # mcast @
155 mac = in4_getnsmac(inet_aton(ip))
156 return mac
157
158 # Check the routing table
159 iff, _, gw = conf.route.route(ip)
160
161 # Limited broadcast
162 if ip == "255.255.255.255":
163 return "ff:ff:ff:ff:ff:ff"
164
165 # Directed broadcast
166 if (iff == conf.loopback_name) or (ip in conf.route.get_if_bcast(iff)):
167 return "ff:ff:ff:ff:ff:ff"
168
169 # An ARP request is necessary
170 if gw != "0.0.0.0":
171 ip = gw
172
173 # Check the cache
174 mac = _arp_cache.get(ip)
175 if mac:
176 return mac
177
178 try:
179 res = srp1(Ether(dst=ETHER_BROADCAST) / ARP(op="who-has", pdst=ip),
180 type=ETH_P_ARP,
181 iface=iff,
182 timeout=2,
183 verbose=0,
184 chainCC=chainCC,
185 nofilter=1)
186 except Exception as ex:
187 warning("getmacbyip failed on %s", ex)
188 return None
189 if res is not None:
190 mac = res.payload.hwsrc
191 _arp_cache[ip] = mac
192 return mac
193 return None
194
195

Callers 4

igmpizeMethod · 0.90
inet_register_l3Function · 0.90
__init__Method · 0.90
l2_register_l3_arpFunction · 0.85

Calls 10

inet_atonFunction · 0.90
in4_ismaddrFunction · 0.90
in4_getnsmacFunction · 0.90
srp1Function · 0.90
warningFunction · 0.90
EtherClass · 0.85
ARPClass · 0.85
get_if_bcastMethod · 0.80
routeMethod · 0.45
getMethod · 0.45

Tested by

no test coverage detected

Used in the wild real call sites across dependent graphs

searching dependent graphs…