6

我正在使用ksoap2-android,我需要使用 java 获取 IP 地址,这样我就不必每次都手动输入。

我所说的 IP 地址是指,例如,如果我使用命令 shell执行ipconfig
: Connection-specific DNS Suffix。:
链路本地 IPv6 地址。. . . . : f0::ed2:e3bf:8206:44%13
IPv4 地址。. . . . . . . . . . :192.168.1.107 <--这是一个
子网掩码。. . . . . . . . . . :255.255.255.0
默认网关。. . . . . . . . : 192.168.1.1

问题是正在开发一个 android 应用程序,并且模拟器具有与机器不同类型的 IP。
我需要获取机器的IP,怎么做?

多谢

4

4 回答 4

8
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 "";
    }
于 2011-03-15T05:53:40.763 回答
4

要获取您的 android 设备的 IP 地址,请使用此代码。

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) ;
}
于 2011-03-15T06:00:18.747 回答
2

试试这个链接

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

你也可以试试这个命令adb shell netcfg

于 2011-03-15T05:53:20.830 回答
2
InetAddress iA=InetAddress.getLocalHost();
System.out.println(iA.getHostAddress());

也可以看看

于 2011-03-15T05:55:23.370 回答