1 /*
2 * Copyright (c) 2021-2022 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 <netdb.h>
17 #include "net_address.h"
18 #include "netstack_log.h"
19 #include "securec.h"
20
21 namespace OHOS::NetStack::Socket {
22
NetAddress()23 NetAddress::NetAddress() : family_(Family::IPv4), port_(0) {}
24
SetAddress(const std::string & address)25 void NetAddress::SetAddress(const std::string &address)
26 {
27 struct addrinfo hints;
28 sa_family_t saFamily = GetSaFamily();
29 if (memset_s(&hints, sizeof hints, 0, sizeof hints) != EOK) {
30 NETSTACK_LOGE("memory operation fail");
31 }
32 hints.ai_family = saFamily;
33 char ipStr[INET6_ADDRSTRLEN];
34 struct addrinfo *res = nullptr;
35 int status = getaddrinfo(address.c_str(), nullptr, &hints, &res);
36 if (status != 0 || res == nullptr) {
37 NETSTACK_LOGE("getaddrinfo status is %{public}d, error is %{public}s", status, gai_strerror(status));
38 return;
39 }
40
41 void *addr = nullptr;
42 if (res->ai_family == AF_INET) {
43 auto *ipv4 = reinterpret_cast<struct sockaddr_in *>(res->ai_addr);
44 addr = &(ipv4->sin_addr);
45 } else {
46 struct sockaddr_in6 *ipv6 = reinterpret_cast<struct sockaddr_in6 *>(res->ai_addr);
47 addr = &(ipv6->sin6_addr);
48 }
49 inet_ntop(res->ai_family, addr, ipStr, sizeof ipStr);
50 address_ = ipStr;
51 freeaddrinfo(res);
52 }
53
SetFamilyByJsValue(uint32_t family)54 void NetAddress::SetFamilyByJsValue(uint32_t family)
55 {
56 if (static_cast<Family>(family) == Family::IPv6) {
57 family_ = Family::IPv6;
58 }
59 }
60
SetFamilyBySaFamily(sa_family_t family)61 void NetAddress::SetFamilyBySaFamily(sa_family_t family)
62 {
63 if (family == AF_INET6) {
64 family_ = Family::IPv6;
65 }
66 }
67
SetPort(uint16_t port)68 void NetAddress::SetPort(uint16_t port)
69 {
70 port_ = port;
71 }
72
GetAddress() const73 const std::string &NetAddress::GetAddress() const
74 {
75 return address_;
76 }
77
GetSaFamily() const78 sa_family_t NetAddress::GetSaFamily() const
79 {
80 if (family_ == Family::IPv6) {
81 return AF_INET6;
82 }
83 return AF_INET;
84 }
85
GetJsValueFamily() const86 uint32_t NetAddress::GetJsValueFamily() const
87 {
88 return static_cast<uint32_t>(family_);
89 }
90
GetPort() const91 uint16_t NetAddress::GetPort() const
92 {
93 return port_;
94 }
95 } // namespace OHOS::NetStack::Socket
96