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 #include "ipv4_info.h"
17 #include "conn_log.h"
18 #include "softbus_common.h"
19 #include "softbus_error_code.h"
20 #include <arpa/inet.h>
21
22 namespace OHOS::SoftBus {
Ipv4Info(const std::string & ip)23 Ipv4Info::Ipv4Info(const std::string &ip)
24 {
25 FromIpString(ip);
26 }
27
operator ==(const Ipv4Info & other) const28 bool Ipv4Info::operator==(const Ipv4Info &other) const
29 {
30 if (ip_ == other.ip_ && prefixLength_ == other.prefixLength_) {
31 return true;
32 }
33 return false;
34 }
35
Marshalling(std::vector<uint8_t> & output) const36 int Ipv4Info::Marshalling(std::vector<uint8_t> &output) const
37 {
38 auto ip = ntohl(ip_);
39 auto p = reinterpret_cast<uint8_t *>(&ip);
40 output.insert(output.begin(), p, p + sizeof(ip));
41 output.push_back(prefixLength_);
42 return SOFTBUS_OK;
43 }
44
Unmarshalling(const uint8_t * input,size_t size)45 int Ipv4Info::Unmarshalling(const uint8_t *input, size_t size)
46 {
47 if (size < Ipv4InfoSize()) {
48 return SOFTBUS_INVALID_PARAM;
49 }
50
51 auto p = reinterpret_cast<uint8_t *>(&ip_);
52 std::copy(input, input + sizeof(ip_), p);
53 prefixLength_ = input[Ipv4InfoSize() - 1];
54 ip_ = htonl(ip_);
55 return SOFTBUS_OK;
56 }
57
FromIpString(const std::string & ipString)58 int Ipv4Info::FromIpString(const std::string &ipString)
59 {
60 if (ipString.empty()) {
61 ip_ = 0;
62 return SOFTBUS_OK;
63 }
64 if (inet_pton(AF_INET, ipString.c_str(), &ip_) != 1) {
65 CONN_LOGW(CONN_WIFI_DIRECT, "inet_pton failed");
66 return SOFTBUS_CONN_INET_PTON_FAILED;
67 }
68 ip_ = htonl(ip_);
69 return SOFTBUS_OK;
70 }
71
ToIpString() const72 std::string Ipv4Info::ToIpString() const
73 {
74 if (ip_ == 0) {
75 return "";
76 }
77 uint32_t ip = ntohl(ip_);
78 char ipStr[IP_STR_MAX_LEN] {};
79 const char *ret = inet_ntop(AF_INET, &ip, ipStr, IP_STR_MAX_LEN);
80 CONN_CHECK_AND_RETURN_RET_LOGW(ret != nullptr, "", CONN_WIFI_DIRECT, "inet_ntop failed");
81 return ipStr;
82 }
83
GetSubNet() const84 uint32_t Ipv4Info::GetSubNet() const
85 {
86 return (ip_ >> SUBNET_SHIFT) & 0xFF;
87 }
88 } // namespace OHOS::SoftBus
89