Get the IPaddress of the computer in an Android project using java

独自空忆成欢 提交于 2019-12-06 00:24:13

问题


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


回答1:


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 "";
    }



回答2:


To get the Ipaddress of your android device you use this code.

WifiManager wifiManager = (WifiManager) getSystemService(WIFI_SERVICE);
WifiInfo wifiInfo = wifiManager.getConnectionInfo();
int ipAddress = wifiInfo.getIpAddress();
String ip = intToIp(ipAddress);

public String intToIp(int i) {

   return ((i >> 24 ) & 0xFF ) + "." +
               ((i >> 16 ) & 0xFF) + "." +
               ((i >> 8 ) & 0xFF) + "." +
               ( i & 0xFF) ;
}



回答3:


Try this link

http://www.droidnova.com/get-the-ip-address-of-your-device,304.html

also you can try this command adb shell netcfg




回答4:


InetAddress iA=InetAddress.getLocalHost();
System.out.println(iA.getHostAddress());

See Also

  • getHostAddress()


来源:https://stackoverflow.com/questions/5307992/get-the-ipaddress-of-the-computer-in-an-android-project-using-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!