通过arp实现输入ip地址输出mac地址

           当一台手机连上wifi热点时,想通过ip知道对方的mac地址,之前网络上找了篇通过netbios实现通过ip寻找mac地址,然而该方法只局限于windows系统,后来了解到通过arp协议可以实现这个功能。于是就有如下的代码:

ipmac.c:

#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include  
#include  
#include 
#include 

struct arpreq arpreq; 
int main(int argc, char* argv[])
{

        if(argc < 2)
        {
                printf("Usage: %s IP\n",argv[0]);
                return 0;
        }
  int sd;
  struct arpreq arpreq;
  struct sockaddr_in *sin;
  struct in_addr ina;
  unsigned char *hw_addr;
  sd = socket(AF_INET, SOCK_DGRAM, 0);
  if (sd < 0)
  {
      perror("socket() error\n");
      exit(1);
  }
  printf("IP : %s\n", argv[1]);
  memset(&arpreq, 0, sizeof(struct arpreq));
  sin = (struct sockaddr_in *) &arpreq.arp_pa;
  memset(sin, 0, sizeof(struct sockaddr_in));
  sin->sin_family = AF_INET;
  ina.s_addr = inet_addr(argv[1]);
  memcpy(&sin->sin_addr, (char *)&ina, sizeof(struct in_addr));
  strcpy(arpreq.arp_dev, "wl0.1"); //wifi热点所用的网卡为wl0.1
  ioctl(sd, SIOCGARP, &arpreq);   
  printf("\nentry has been successfully retreived\n");
  hw_addr = (unsigned char *) arpreq.arp_ha.sa_data;
  printf("MAC: %x:%x:%x:%x:%x:%x\n",  
  hw_addr[0], hw_addr[1], hw_addr[2], hw_addr[3], hw_addr[4], hw_addr[5]);
  return 0;
} 

Android.mk:

LOCAL_PATH := $(call my-dir)
include $(CLEAR_VARS)

LOCAL_ARM_MODE := arm

LOCAL_SRC_FILES := \
        ipmac.c

LOCAL_MODULE:= ipmac

LOCAL_PRELINK_MODULE := false


LOCAL_C_INCLUDES += \
        $(LOCAL_PATH)/include

include $(BUILD_EXECUTABLE) //编译成可执行文件


编译后执行该./ipmac xxx .xxx.xxx.xxx(ip) 即可打印出该ip的mac地址。

 


 

你可能感兴趣的:(android)