Warning, /network/kdeconnect-android/src/org/kde/kdeconnect/Helpers/NetworkHelper.kt is written in an unsupported language. File is not indexed.

0001 /*
0002  * SPDX-FileCopyrightText: 2023 Albert Vaca Cintora <albertvaka@gmail.com>
0003  *
0004  * SPDX-License-Identifier: GPL-2.0-only OR GPL-3.0-only OR LicenseRef-KDE-Accepted-GPL
0005  */
0006 package org.kde.kdeconnect.Helpers
0007 
0008 import java.net.Inet4Address
0009 import java.net.InetAddress
0010 import java.net.NetworkInterface
0011 import java.net.SocketException
0012 
0013 object NetworkHelper {
0014     //Prefer IPv4 over IPv6, because sshfs doesn't seem to like IPv6
0015     // Anything with rmnet is related to cellular connections or USB
0016     // tethering mechanisms.  See:
0017     //
0018     // https://android.googlesource.com/kernel/msm/+/android-msm-flo-3.4-kitkat-mr1/Documentation/usb/gadget_rmnet.txt
0019     //
0020     // If we run across an interface that has this, we can safely
0021     // ignore it.  In fact, it's much safer to do.  If we don't, we
0022     // might get invalid IP adddresses out of it.
0023     @JvmStatic
0024     val localIpAddress: InetAddress?
0025         get() {
0026             var ip6: InetAddress? = null
0027             try {
0028                 for (intf in NetworkInterface.getNetworkInterfaces()) {
0029 
0030                     // Anything with rmnet is related to cellular connections or USB
0031                     // tethering mechanisms.  See:
0032                     //
0033                     // https://android.googlesource.com/kernel/msm/+/android-msm-flo-3.4-kitkat-mr1/Documentation/usb/gadget_rmnet.txt
0034                     //
0035                     // If we run across an interface that has this, we can safely
0036                     // ignore it.  In fact, it's much safer to do.  If we don't, we
0037                     // might get invalid IP adddresses out of it.
0038                     if (intf.displayName.contains("rmnet")) {
0039                         continue
0040                     }
0041                     val enumIpAddr = intf.inetAddresses
0042                     while (enumIpAddr.hasMoreElements()) {
0043                         val inetAddress = enumIpAddr.nextElement()
0044                         if (!inetAddress.isLoopbackAddress) {
0045                             ip6 =
0046                                 if (inetAddress is Inet4Address) { //Prefer IPv4 over IPv6, because sshfs doesn't seem to like IPv6
0047                                     return inetAddress
0048                                 } else {
0049                                     inetAddress
0050                                 }
0051                         }
0052                     }
0053                 }
0054             } catch (ignored: SocketException) {
0055             }
0056             return ip6
0057         }
0058 }