Kotlin Study

Android get IP Address (min 29 sdk)

85chong 2023. 11. 17. 10:42
728x90
반응형
SMALL

device ip 가져오는 방법

 

 

1. AndroidManifest.xml 

 

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

 

 

2. getIP function

fun getIp(context: Context): String? {
    NetworkInterface.getNetworkInterfaces()?.toList()?.map { networkInterface ->
        networkInterface.inetAddresses?.toList()?.find {
            !it.isLoopbackAddress && it is Inet4Address
        }?.let { return it.hostAddress }
    }
    return ""
}

 

 

- 끝 -