ioctl之获取arp表项
2015-07-12 18:51
281 查看
ioctl是跟内核交互的一种方式,网络设计中广泛使用了ioctl函数来和内核协议栈进行交互。其原型为:
int ioctl(int d,int request,...)
[root@localhost 12.6.5]# ./ioctl_arp 10.10.10.2
10.10.10.2:00:50:56:fb:8f:da
int ioctl(int d,int request,...)
#include <stdio.h> #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #include <net/if_arp.h> #include <string.h> #include <unistd.h> #include <sys/ioctl.h> int main(int argc, char *argv[]) { int s; struct arpreq arpreq; struct sockaddr_in *addr = (struct sockaddr_in*)&arpreq.arp_pa; unsigned char *hw; int err = -1; if(argc < 2){ printf("错误的使用方式,格式为:\nmyarp ip(myarp 127.0.0.1)\n"); return -1; } /*建立一个数据报套接字*/ s = socket(AF_INET, SOCK_DGRAM, 0); if (s < 0) { printf("socket() 出错\n"); return -1; } /*填充arpreq的成员arp_pa*/ addr->sin_family = AF_INET; addr->sin_addr.s_addr = inet_addr(argv[1]); if(addr->sin_addr.s_addr == INADDR_NONE){ printf("IP 地址格式错误\n"); } /*网络接口为eth1*/ strcpy(arpreq.arp_dev, "eth1"); err = ioctl(s, SIOCGARP, &arpreq); //<span style="font-family: Arial, Helvetica, sans-serif;">SIOCGARP:获取arp表中的一项,如果没有就会出错</span> if(err < 0){ /*失败*/ printf("IOCTL 错误\n"); return -1; }else{/*成功*/ hw = (unsigned char*)&arpreq.arp_ha.sa_data; /*硬件地址*/ printf("%s:",argv[1]);/*打印IP*/ printf("%02x:%02x:%02x:%02x:%02x:%02x\n", /*打印硬件地址*/ hw[0],hw[1],hw[2],hw[3],hw[4],hw[5]); }; close(s); return 0; }运行结果:
[root@localhost 12.6.5]# ./ioctl_arp 10.10.10.2
10.10.10.2:00:50:56:fb:8f:da
相关文章推荐
- Learn Gradle - CH 2 基本的构建脚本介绍
- UVA - 12001 UVa Panel Discussion
- Unity3D教程宝典之Shader篇
- iOS模拟器常用操作
- 在java项目中使用AES256 CBC加密
- WinDebug查找内存泄露
- 统计学习方法概论
- Reverse Bits (leetcode 190)
- python函数定义
- 模方程组解法
- 均方根值(RMS)+ 均方根误差(RMSE)+标准差(Standard Deviation)
- Linux高级文件系统管理之基本RAID的工作原理
- Codeforces Round #310 (Div. 1) C. Case of Chocolate stl应用
- 【C++11】新特性——引入nullprt
- [LeetCode][Java] Search Insert Position
- Mybatis框架实现功能的流程
- 送给使用phpstorm+thinkphp开发者的福利
- iOS设计模式-原型
- 【Passport】微软过时的技术
- (4)单例模式