• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 #include "dhcp_thread.h"
23 
24 namespace OHOS {
25 namespace DHCP {
26 constexpr int32_t IPV4_ALEN = 4;
27 constexpr int32_t INTEGER_MAX = 0x7FFFFFFF;
28 
29 struct ArpPacket {
30     uint16_t ar_hrd; // hardware type
31     uint16_t ar_pro; // protocol type
32     uint8_t ar_hln; // length of hardware address
33     uint8_t ar_pln; // length of protocol address
34     uint16_t ar_op; // opcode
35     uint8_t ar_sha[ETH_ALEN]; // sender hardware address
36     uint8_t ar_spa[IPV4_ALEN]; // sender protocol address
37     uint8_t ar_tha[ETH_ALEN]; // target hardware address
38     uint8_t ar_tpa[IPV4_ALEN]; // target protocol address
39 } __attribute__ ((__packed__));
40 
41 class DhcpArpChecker {
42 public:
43     DhcpArpChecker();
44     ~DhcpArpChecker();
45     bool Start(std::string& ifname, std::string& hwAddr, std::string& senderIp, std::string& targetIp);
46     void Stop();
47     bool DoArpCheck(int32_t timeoutMillis, bool isFillSenderIp, uint64_t &timeCost);
48     void GetGwMacAddrList(int32_t timeoutMillis, bool isFillSenderIp, std::vector<std::string>& gwMacLists);
49 
50 private:
51     bool SetArpPacket(ArpPacket& arpPacket, bool isFillSenderIp);
52     int32_t CreateSocket(const char *iface, uint16_t protocol);
53     int32_t SendData(uint8_t *buff, int32_t count, uint8_t *destHwaddr);
54     int32_t RecvData(uint8_t *buff, int32_t count, int32_t timeoutMillis);
55     int32_t CloseSocket(void);
56     bool SetNonBlock(int32_t fd);
57     void SaveGwMacAddr(std::string gwMacAddr, std::vector<std::string>& gwMacLists);
58 private:
59     std::unique_ptr<DhcpThread> dhcpArpCheckerThread_ = nullptr;
60     bool m_isSocketCreated;
61     struct in_addr m_localIpAddr;
62     struct in_addr m_targetIpAddr;
63     uint8_t m_localMacAddr[ETH_ALEN];
64     uint8_t m_l2Broadcast[ETH_ALEN];
65     int32_t m_socketFd;
66     uint16_t m_ifaceIndex;
67     uint16_t m_protocol;
68 };
69 }
70 }
71 #endif
72