Skip to content

Instantly share code, notes, and snippets.

@leasual
Created April 17, 2020 00:42
Show Gist options
  • Save leasual/e32d40c3b01ed6b2d0e9d2cfecf7a990 to your computer and use it in GitHub Desktop.
Save leasual/e32d40c3b01ed6b2d0e9d2cfecf7a990 to your computer and use it in GitHub Desktop.
Get IP Address Android Device
object NetworkUtil {
/**
* Convert byte array to hex string
* @param bytes
* @return
*/
fun bytesToHex(bytes: ByteArray): String {
val sbuf = StringBuilder()
for (idx in bytes.indices) {
val intVal: Int = (bytes[idx] and 0xff.toByte()).toInt()
if (intVal < 0x10) sbuf.append("0")
sbuf.append(Integer.toHexString(intVal).toUpperCase())
}
return sbuf.toString()
}
/**
* Get utf8 byte array.
* @param str
* @return array of NULL if error was found
*/
fun getUTF8Bytes(str: String): ByteArray? {
return try {
str.toByteArray(charset("UTF-8"))
} catch (ex: Exception) {
null
}
}
/**
* Load UTF8withBOM or any ansi text file.
* @param filename
* @return
* @throws java.io.IOException
*/
@Throws(IOException::class)
fun loadFileAsString(filename: String?): String {
val bufferLen = 1024
val `is` = BufferedInputStream(FileInputStream(filename), bufferLen)
return try {
val baos = ByteArrayOutputStream(bufferLen)
val bytes = ByteArray(bufferLen)
var isUTF8 = false
var read: Int = 0
var count = 0
while (`is`.read(bytes).also { read = it } != -1) {
if (count == 0 && bytes[0] == 0xEF.toByte() && bytes[1] == 0xBB.toByte() && bytes[2] == 0xBF.toByte()
) {
isUTF8 = true
baos.write(bytes, 3, read - 3) // drop UTF8 bom marker
} else {
baos.write(bytes, 0, read)
}
count += read
}
if (isUTF8) String(baos.toByteArray(), Charset.forName("UTF-8")) else String(baos.toByteArray())
} finally {
try {
`is`.close()
} catch (ex: Exception) {
}
}
}
/**
* Returns MAC address of the given interface name.
* @param interfaceName eth0, wlan0 or NULL=use first interface
* @return mac address or empty string
*/
fun getMACAddress(interfaceName: String?): String {
try {
val interfaces: List<NetworkInterface> =
Collections.list(NetworkInterface.getNetworkInterfaces())
for (intf in interfaces) {
if (interfaceName != null) {
if (intf.name.toLowerCase() != interfaceName) continue
}
val mac: ByteArray = intf.hardwareAddress ?: return ""
val buf = StringBuilder()
for (idx in mac.indices) buf.append(String.format("%02X:", mac[idx]))
if (buf.isNotEmpty()) buf.deleteCharAt(buf.length - 1)
return buf.toString()
}
} catch (ex: Exception) {
} // for now eat exceptions
return ""
/*try {
// this is so Linux hack
return loadFileAsString("/sys/class/net/" +interfaceName + "/address").toUpperCase().trim();
} catch (IOException ex) {
return null;
}*/
}
/**
* Get IP address from first non-localhost interface
* @param ipv4 true=return ipv4, false=return ipv6
* @return address or empty string
*/
fun getIPAddress(useIPv4: Boolean): String {
try {
val interfaces: List<NetworkInterface> =
Collections.list(NetworkInterface.getNetworkInterfaces())
for (intf in interfaces) {
val addrs: List<InetAddress> = Collections.list(intf.inetAddresses)
for (addr in addrs) {
if (!addr.isLoopbackAddress) {
val sAddr: String = addr.hostAddress.toUpperCase()
val isIPv4: Boolean = addr is Inet4Address
if (useIPv4) {
if (isIPv4) return sAddr
} else {
if (!isIPv4) {
val delim = sAddr.indexOf('%') // drop ip6 port suffix
return if (delim < 0) sAddr else sAddr.substring(0, delim)
}
}
}
}
}
} catch (ex: Exception) {
} // for now eat exceptions
return ""
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment