获取计算机的ip地址在Android项目中使用Java [英] Get the IPaddress of the computer in an Android project using java

查看:199
本文介绍了获取计算机的ip地址在Android项目中使用Java的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用 ksoap2-的Andr​​oid ,我需要得到使用Java这样我就不必手动输入每次的IP地址。

我的意思的IP地址,例如,如果我做的 IPCONFIG 使用命令shell:
 连接特定的DNS后缀。 :
 链路本地IPv6地址。 。 。 。 。 :F0 :: ED2:e3bf:8206:44%13
 的IPv4地址。 。 。 。 。 。 。 。 。 。 。 :192.168.1.107 < - 这个
 子网掩码 。 。 。 。 。 。 。 。 。 。 。 :255.255.255.0
 默认网关 。 。 。 。 。 。 。 。 。 :192.168.1.1

事情是正在开发Android应用程序,和仿真器有不同的类型的IP的不是机器的。照片 我需要得到本机的IP,这是怎么做?

非常感谢

解决方案

 公共字符串getLocalIpAddress(){
        尝试 {
            对于(枚举<的NetworkInterface> EN =的NetworkInterface
                    .getNetworkInterfaces(); en.hasMoreElements()){
                NetworkInterface的INTF = en.nextElement();
                对于(枚举< InetAddress类> enumIpAddr = INTF
                        .getInetAddresses(); enumIpAddr.hasMoreElements()){
                    InetAddress类InetAddress类= enumIpAddr.nextElement();
                    如果(!inetAddress.isLoopbackAddress()){
                        返回inetAddress.getHostAddress()的toString()。
                    }
                }
            }
        }赶上(SocketException前){
            Log.e(标签,ex.toString());
        }
        返回 ;
    }
 

I am using ksoap2-android and i need to get the IP address using java so that I don't have to type it manually everytime.

What i mean by IP address is , for example if I do ipconfig using the command shell:
Connection-specific DNS Suffix . :
Link-local IPv6 Address . . . . . : f0::ed2:e3bf:8206:44%13
IPv4 Address. . . . . . . . . . . : 192.168.1.107 <--THIS ONE
Subnet Mask . . . . . . . . . . . : 255.255.255.0
Default Gateway . . . . . . . . . : 192.168.1.1

The thing is am developing an android app, and the emulator has a different type of IP's than the machine's .
I need to get the machine's IP , how is this to be done?

thanks a lot

解决方案

public String getLocalIpAddress() {
        try {
            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()) {
                        return inetAddress.getHostAddress().toString();
                    }
                }
            }
        } catch (SocketException ex) {
            Log.e(tag, ex.toString());
        }
        return "";
    }

这篇关于获取计算机的ip地址在Android项目中使用Java的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆