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)
| 136 | |
| 137 | @conf.commands.register |
| 138 | def 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 |
no test coverage detected
searching dependent graphs…