1 /* 2 * Copyright (C) 2024 Huawei Device Co., Ltd. 3 * Licensed under the Apache License, Version 2.0 (the "License"); 4 * you may not use this file except in compliance with the License. 5 * You may obtain a copy of the License at 6 * 7 * http://www.apache.org/licenses/LICENSE-2.0 8 * 9 * Unless required by applicable law or agreed to in writing, software 10 * distributed under the License is distributed on an "AS IS" BASIS, 11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 * See the License for the specific language governing permissions and 13 * limitations under the License. 14 */ 15 16 #ifndef OHOS_DHCP_ARP_CHECKER_H 17 #define OHOS_DHCP_ARP_CHECKER_H 18 19 #include <arpa/inet.h> 20 #include <netinet/if_ether.h> 21 #include <string> 22 23 namespace OHOS { 24 namespace DHCP { 25 constexpr int32_t IPV4_ALEN = 4; 26 constexpr int32_t INTEGER_MAX = 0x7FFFFFFF; 27 28 struct ArpPacket { 29 uint16_t ar_hrd; // hardware type 30 uint16_t ar_pro; // protocol type 31 uint8_t ar_hln; // length of hardware address 32 uint8_t ar_pln; // length of protocol address 33 uint16_t ar_op; // opcode 34 uint8_t ar_sha[ETH_ALEN]; // sender hardware address 35 uint8_t ar_spa[IPV4_ALEN]; // sender protocol address 36 uint8_t ar_tha[ETH_ALEN]; // target hardware address 37 uint8_t ar_tpa[IPV4_ALEN]; // target protocol address 38 } __attribute__ ((__packed__)); 39 40 class DhcpArpChecker { 41 public: 42 DhcpArpChecker(); 43 ~DhcpArpChecker(); 44 bool Start(std::string& ifname, std::string& hwAddr, std::string& senderIp, std::string& targetIp); 45 void Stop(); 46 bool DoArpCheck(int32_t timeoutMillis, bool isFillSenderIp, uint64_t &timeCost); 47 void GetGwMacAddrList(int32_t timeoutMillis, bool isFillSenderIp, std::vector<std::string>& gwMacLists); 48 49 private: 50 bool SetArpPacket(ArpPacket& arpPacket, bool isFillSenderIp); 51 int32_t CreateSocket(const char *iface, uint16_t protocol); 52 int32_t SendData(uint8_t *buff, int32_t count, uint8_t *destHwaddr); 53 int32_t RecvData(uint8_t *buff, int32_t count, int32_t timeoutMillis); 54 int32_t CloseSocket(void); 55 bool SetNonBlock(int32_t fd); 56 void SaveGwMacAddr(std::string gwMacAddr, std::vector<std::string>& gwMacLists); 57 private: 58 bool m_isSocketCreated; 59 struct in_addr m_localIpAddr; 60 struct in_addr m_targetIpAddr; 61 uint8_t m_localMacAddr[ETH_ALEN]; 62 uint8_t m_l2Broadcast[ETH_ALEN]; 63 int32_t m_socketFd; 64 uint16_t m_ifaceIndex; 65 uint16_t m_protocol; 66 }; 67 } 68 } 69 #endif 70