Skip to content

Instantly share code, notes, and snippets.

@xiaofeidev
Created January 15, 2019 03:10
Show Gist options
  • Save xiaofeidev/7d5f6bfaaf9e754ddd2387365cf0bd25 to your computer and use it in GitHub Desktop.
Save xiaofeidev/7d5f6bfaaf9e754ddd2387365cf0bd25 to your computer and use it in GitHub Desktop.
Kotlin 实现的工具类,获取本机内网 IP 和公网 IP
import org.json.JSONException
import org.json.JSONObject
import java.io.BufferedInputStream
import java.io.ByteArrayOutputStream
import java.io.IOException
import java.lang.Exception
import java.net.*
/**
* Created by xiaofei on 2019/1/15.
*/
object IpUtil {
/**
* 获取本机内网 IP 地址,Android 内同步调用
*/
fun getLocalIP(): String? {
var hostIp: String? = null
try {
val nis = NetworkInterface.getNetworkInterfaces()
var ia: InetAddress?
while (nis.hasMoreElements()) {
val ni = nis.nextElement() as NetworkInterface
val ias = ni.inetAddresses
while (ias.hasMoreElements()) {
ia = ias.nextElement()
if (ia is Inet6Address) {
continue// skip ipv6
}
val ip = ia?.hostAddress
if ("127.0.0.1" != ip) {
hostIp = ia?.hostAddress
break
}
}
}
} catch (e: SocketException) {
e.printStackTrace()
}
return hostIp
}
/**
* 获取本机公网 IP 地址,Android 内异步调用
*/
fun getNetIp(): String? {
var byteArrayOutputStream: ByteArrayOutputStream? = null
var bufferedInputStream: BufferedInputStream? = null
var result: String? = null
var httpConnection: HttpURLConnection? = null
try {
val infoUrl = URL("http://pv.sohu.com/cityjson?ie=utf-8")
httpConnection = infoUrl.openConnection() as HttpURLConnection
//设置连接时间,10秒
httpConnection.connectTimeout = 10 * 1000
httpConnection.readTimeout = 10 * 1000
//数据编码格式,这里utf-8
httpConnection.setRequestProperty("Charset", "utf-8");
//添加cookie,cookie规则需开发者自定
// urlConnection.setRequestProperty("Cookie", Constants.COOCKIE_KEY + token);
//设置返回结果的类型,这里是json
httpConnection.setRequestProperty("accept", "application/json");
//这里设置post传递的内容类型,这里json
httpConnection.setRequestProperty("Content-Type", "application/json");
//开启客户端与Url所指向的资源的网络连接
httpConnection.connect();
val responseCode = httpConnection.responseCode
if (responseCode == HttpURLConnection.HTTP_OK) {
bufferedInputStream = BufferedInputStream(httpConnection.inputStream)
byteArrayOutputStream = ByteArrayOutputStream()
//httpUrlConnection返回传输字节的长度,创建一个byte 数组。
val b = ByteArray(httpConnection.contentLength)
var length = 0
while (bufferedInputStream.read(b).apply { length = this } > 0) {
byteArrayOutputStream.write(b, 0, length)
}
result = byteArrayOutputStream.toString("utf-8")
// 从反馈的结果中提取出IP地址
val start = result.indexOf("{")
val end = result.indexOf("}")
var json: String? = null
if (start != -1 && end != -1){
json = result.substring(start, end + 1)
}
if (json != null) {
try {
val jsonObject = JSONObject(json)
result = jsonObject.optString("cip")
} catch (e: JSONException) {
e.printStackTrace()
}
}else{
result = null
}
return result
}
} catch (e: MalformedURLException) {
e.printStackTrace()
} catch (e: IOException) {
e.printStackTrace()
} finally {
try {
byteArrayOutputStream?.close()
bufferedInputStream?.close()
//解除连接,释放网络资源
httpConnection?.disconnect()
} catch (e: Exception) {
e.printStackTrace()
}
}
return result
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment