Android 获取局域网内网IP地址

Android 获取局域网内网IP地址

废话

拿局域网IP一般用在tcp通讯或udp通讯上,下次再整理下这类通讯的框架

上代码

/**
 * 网络工具
 * 获得局域网IP地址
 * @author  dlong
 * created at 2019/3/8 2:46 PM
 */
public class NetworkUtils {

    /**
     * 获取内网IP地址
     * @return
     * @throws SocketException
     */
    public static String getLocalIPAddress() throws SocketException {
        for(Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements();){
            NetworkInterface intf = en.nextElement();
            for(Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements();){
                InetAddress inetAddress = enumIpAddr.nextElement();
                if(!inetAddress.isLoopbackAddress() && (inetAddress instanceof Inet4Address)){
                    return inetAddress.getHostAddress().toString();
                }
            }
        }
        return "null";
    }
}

kotlin版

import java.net.Inet4Address
import java.net.InetAddress
import java.net.NetworkInterface
import java.util.*


/**
 * @author D10NG
 * @date on 2019-12-10 14:37
 */
object NetUtils {

    /**
     * 获取内网IP地址
     */
    val localIPAddress: String
        get() {
            val en: Enumeration<NetworkInterface> = NetworkInterface.getNetworkInterfaces()
            while (en.hasMoreElements()) {
                val intf: NetworkInterface = en.nextElement()
                val enumIpAddr: Enumeration<InetAddress> = intf.inetAddresses
                while (enumIpAddr.hasMoreElements()) {
                    val inetAddress: InetAddress = enumIpAddr.nextElement()
                    if (!inetAddress.isLoopbackAddress && inetAddress is Inet4Address) {
                        return inetAddress.hostAddress.toString()
                    }
                }
            }
            return "null"
        }
}

完事

已标记关键词 清除标记
相关推荐
©️2020 CSDN 皮肤主题: 技术黑板 设计师:CSDN官方博客 返回首页