How to clear arp cache in linux by program, not command

Viewed 2040

How to clear arp cache in linux by program, not by using arp command? Are there library functions avaliable to implement this?

=========================================================================== EDIT

In linux, I want to clear arp cache periodically and send ping packets to find hosts in LAN(by collecting arp response and ICMP reply). As some hosts don't reply ping, I try to receive arp response and ICMP reply in my program. But if arp cache has the IP information, it doesn't send arp request for that IP, and the topology may not be complete. So I want to clear arp cache periodically. How can I clear arp cache periodically in my program?Thanks for your time.

3 Answers

Here is my example how I made it for python:

import fcntl
import socket
import struct
import ipaddress

def clear_arp(ip, ifname=''):
    while True:
        try:
            sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)    
            ip_bytes = int(ipaddress.IPv4Address(ip)).to_bytes(4, byteorder='big')
            fcntl.ioctl(
                sock.fileno(),
                    0x8953, # SIOCDARP
                    struct.pack('hh48s16s', socket.AF_INET, 0, ip_bytes, ifname[:15].encode())
                )
        except OSError as e:
            break
        finally:
            sock.close()

                    struct.pack('hh48s16s', socket.AF_INET, 0, ip_bytes, ifname[:15].encode())
                )
        except OSError as e:
            break
        finally:
            sock.close()
Related