1 /*
2  * Copyright (c) 2021-2023 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 "lnn_ip_utils_adapter.h"
17 
18 #include "comm_log.h"
19 #include "lwip/netif.h"
20 
GetNetworkIpByIfName(const char * ifName,char * ip,char * netmask,uint32_t len)21 int32_t GetNetworkIpByIfName(const char *ifName, char *ip, char *netmask, uint32_t len)
22 {
23     if (ifName == NULL || ip == NULL) {
24         COMM_LOGE(COMM_ADAPTER, "ifName or ip buffer is NULL!");
25         return SOFTBUS_INVALID_PARAM;
26     }
27 
28     struct netif *netif = NULL;
29     char *ipStr = NULL;
30     char *netMaskStr = NULL;
31     ip4_addr_t *ipAddr = NULL;
32     ip4_addr_t *netMask = NULL;
33 
34     netif = netif_find(ifName);
35     if (netif == NULL) {
36         COMM_LOGE(COMM_ADAPTER, "netif is NULL!");
37         return SOFTBUS_ERR;
38     }
39 #ifdef HISPARK_PEGASUS_USE_NETIF_GET_ADDR
40     netifapi_netif_get_addr(netif, ipAddr, netMask, NULL);
41 #else
42     ipAddr = (ip4_addr_t *)netif_ip4_addr(netif);
43     netMask = (ip4_addr_t *)netif_ip4_netmask(netif);
44 #endif
45     ipStr = ip4addr_ntoa(ipAddr);
46     if (strncpy_s(ip, len, ipStr, strlen(ipStr)) != EOK) {
47         COMM_LOGE(COMM_ADAPTER, "copy ip failed!");
48         return SOFTBUS_ERR;
49     }
50     if (netmask != NULL) {
51         netMaskStr = ip4addr_ntoa(netMask);
52         if (strncpy_s(netmask, len, netMaskStr, strlen(netMaskStr)) != EOK) {
53             COMM_LOGE(COMM_ADAPTER, "copy netmask failed!");
54             return SOFTBUS_ERR;
55         }
56     }
57     return SOFTBUS_OK;
58 }
59