获取ARP表

arpGet("ens33", "192.168.74.1");

获取ens33网卡下192.168.74.1这一项,如果没有192.168.74.1,返回小于0.


#include <stdio.h> 

#include<unistd.h>

#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <sys/ioctl.h>
#include <net/if_arp.h>
#include <string.h>


int arpGet(char *ifname, char *ipStr)
{
  struct arpreq req;
struct sockaddr_in *sin;
int ret = 0;
int sock_fd = 0;
 
memset(&req, 0, sizeof(struct arpreq));
 
sin = (struct sockaddr_in *)&req.arp_pa;
sin->sin_family = AF_INET;
sin->sin_addr.s_addr = inet_addr(ipStr);
 
//arp_dev长度为[16],注意越界
strncpy(req.arp_dev, ifname, 15);
 
sock_fd = socket(AF_INET, SOCK_DGRAM, 0);
if(sock_fd < 0)
{
printf("get socket error.\n");
return -1;
}
 
ret = ioctl(sock_fd, SIOCGARP, &req);
if(ret < 0)
{
printf("ioctl error.\n");
close(sock_fd);
return -1;
}
 
unsigned char *hw = (unsigned char *)req.arp_ha.sa_data;
printf("%02x:%02x:%02x:%02x:%02x:%02x\n", hw[0], hw[1], hw[2], hw[3], hw[4], hw[5]);
printf("%#x\n", req.arp_flags);
close(sock_fd);
return 0;
}
int main()
{
arpGet("ens33", "192.168.74.1");
return 1;
}

猜你喜欢

转载自blog.csdn.net/qq_14814909/article/details/80911552
arp