原理其实很简单,那就是广播一个arp包,然后recv,如果没有数据(这里要设置延时),那么说明这个ip是可用的,否则就检测这个数据是否为回复我们发出的arp的应答包.如果是则证明ip已被使用,否则继续等待.
这里可以看下busybox的dhcp中的检测程序。
networking/udhcp/arpping.c
-
-
-
-
-
-
-
-
- #include
- #include
-
- #include "common.h"
- #include "dhcpd.h"
-
-
- struct arpMsg {
-
- uint8_t h_dest[6];
- uint8_t h_source[6];
- uint16_t h_proto;
-
-
- uint16_t htype;
- uint16_t ptype;
- uint8_t hlen;
- uint8_t plen;
- uint16_t operation;
- uint8_t sHaddr[6];
- uint8_t sInaddr[4];
- uint8_t tHaddr[6];
- uint8_t tInaddr[4];
- uint8_t pad[18];
- } PACKED;
-
- enum {
- ARP_MSG_SIZE = 0x2a
- };
-
-
-
-
-
- int arpping(uint32_t test_ip, uint32_t from_ip, uint8_t *from_mac, const char *interface)
- {
-
- int timeout_ms;
-
- struct pollfd pfd[1];
- #define s (pfd[0].fd) /* socket */
- int rv = 1;
- struct sockaddr addr;
- struct arpMsg arp;
-
-
-
- s = socket(PF_PACKET, SOCK_PACKET, htons(ETH_P_ARP));
- if (s == -1) {
- bb_perror_msg(bb_msg_can_not_create_raw_socket);
- return -1;
- }
-
- if (setsockopt_broadcast(s) == -1) {
- bb_perror_msg("cannot enable bcast on raw socket");
- goto ret;
- }
-
-
- memset(&arp, 0, sizeof(arp));
- memset(arp.h_dest, 0xff, 6);
- memcpy(arp.h_source, from_mac, 6);
- arp.h_proto = htons(ETH_P_ARP);
- arp.htype = htons(ARPHRD_ETHER);
- arp.ptype = htons(ETH_P_IP);
- arp.hlen = 6;
- arp.plen = 4;
- arp.operation = htons(ARPOP_REQUEST);
- memcpy(arp.sHaddr, from_mac, 6);
- memcpy(arp.sInaddr, &from_ip, sizeof(from_ip));
-
- memcpy(arp.tInaddr, &test_ip, sizeof(test_ip));
-
- memset(&addr, 0, sizeof(addr));
- safe_strncpy(addr.sa_data, interface, sizeof(addr.sa_data));
-
- if (sendto(s, &arp, sizeof(arp), 0, &addr, sizeof(addr)) < 0) {
-
-
- goto ret;
- }
-
-
-
- timeout_ms = 2000;
- do {
- int r;
- unsigned prevTime = monotonic_us();
-
- pfd[0].events = POLLIN;
-
- r = safe_poll(pfd, 1, timeout_ms);
- if (r < 0)
- break;
- if (r) {
-
- r = read(s, &arp, sizeof(arp));
- if (r < 0)
- break;
-
- if (r >= ARP_MSG_SIZE
- && arp.operation == htons(ARPOP_REPLY)
-
-
- && *((uint32_t *) arp.sInaddr) == test_ip
- ) {
-
- rv = 0;
- break;
- }
- }
- timeout_ms -= ((unsigned)monotonic_us() - prevTime) / 1000;
- } while (timeout_ms > 0);
-
- ret:
- close(s);
- DEBUG("%srp reply received for this address", rv ? "No a" : "A");
- return rv;
- }
阅读(1239) | 评论(0) | 转发(1) |