是否可以使用一些代码获得设备的IP地址?
当前回答
根据我的测试,这是我的建议
import java.net.*;
import java.util.*;
public class hostUtil
{
public static String HOST_NAME = null;
public static String HOST_IPADDRESS = null;
public static String getThisHostName ()
{
if (HOST_NAME == null) obtainHostInfo ();
return HOST_NAME;
}
public static String getThisIpAddress ()
{
if (HOST_IPADDRESS == null) obtainHostInfo ();
return HOST_IPADDRESS;
}
protected static void obtainHostInfo ()
{
HOST_IPADDRESS = "127.0.0.1";
HOST_NAME = "localhost";
try
{
InetAddress primera = InetAddress.getLocalHost();
String hostname = InetAddress.getLocalHost().getHostName ();
if (!primera.isLoopbackAddress () &&
!hostname.equalsIgnoreCase ("localhost") &&
primera.getHostAddress ().indexOf (':') == -1)
{
// Got it without delay!!
HOST_IPADDRESS = primera.getHostAddress ();
HOST_NAME = hostname;
//System.out.println ("First try! " + HOST_NAME + " IP " + HOST_IPADDRESS);
return;
}
for (Enumeration<NetworkInterface> netArr = NetworkInterface.getNetworkInterfaces(); netArr.hasMoreElements();)
{
NetworkInterface netInte = netArr.nextElement ();
for (Enumeration<InetAddress> addArr = netInte.getInetAddresses (); addArr.hasMoreElements ();)
{
InetAddress laAdd = addArr.nextElement ();
String ipstring = laAdd.getHostAddress ();
String hostName = laAdd.getHostName ();
if (laAdd.isLoopbackAddress()) continue;
if (hostName.equalsIgnoreCase ("localhost")) continue;
if (ipstring.indexOf (':') >= 0) continue;
HOST_IPADDRESS = ipstring;
HOST_NAME = hostName;
break;
}
}
} catch (Exception ex) {}
}
}
其他回答
我使用以下代码: 我使用hashCode的原因是因为当我使用getHostAddress时,我得到了一些垃圾值附加到ip地址。但是hashCode对我来说工作得很好,这样我就可以使用Formatter来获得具有正确格式的ip地址。
下面是示例输出:
1.使用 getHostAddress : ***** IP=fe80::65ca:a13d:ea5a:233d%rmnet_sdio0
2.使用hashCode和Formatter: ***** IP=238.194.77.212
如你所见,第二种方法正好满足了我的需求。
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()) {
String ip = Formatter.formatIpAddress(inetAddress.hashCode());
Log.i(TAG, "***** IP="+ ip);
return ip;
}
}
}
} catch (SocketException ex) {
Log.e(TAG, ex.toString());
}
return null;
}
private InetAddress getLocalAddress()throws IOException {
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();
return inetAddress;
}
}
}
} catch (SocketException ex) {
Log.e("SALMAN", ex.toString());
}
return null;
}
Kotlin极简版
fun getIpv4HostAddress(): String {
NetworkInterface.getNetworkInterfaces()?.toList()?.map { networkInterface ->
networkInterface.inetAddresses?.toList()?.find {
!it.isLoopbackAddress && it is Inet4Address
}?.let { return it.hostAddress }
}
return ""
}
简单地使用凌空从这个网站获得ip
RequestQueue queue = Volley.newRequestQueue(this);
String urlip = "http://checkip.amazonaws.com/";
StringRequest stringRequest = new StringRequest(Request.Method.GET, urlip, new Response.Listener<String>() {
@Override
public void onResponse(String response) {
txtIP.setText(response);
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
txtIP.setText("didnt work");
}
});
queue.add(stringRequest);
在你的活动中,下面的函数getIpAddress(context)返回电话的IP地址:
public static String getIpAddress(Context context) {
WifiManager wifiManager = (WifiManager) context.getApplicationContext()
.getSystemService(WIFI_SERVICE);
String ipAddress = intToInetAddress(wifiManager.getDhcpInfo().ipAddress).toString();
ipAddress = ipAddress.substring(1);
return ipAddress;
}
public static InetAddress intToInetAddress(int hostAddress) {
byte[] addressBytes = { (byte)(0xff & hostAddress),
(byte)(0xff & (hostAddress >> 8)),
(byte)(0xff & (hostAddress >> 16)),
(byte)(0xff & (hostAddress >> 24)) };
try {
return InetAddress.getByAddress(addressBytes);
} catch (UnknownHostException e) {
throw new AssertionError();
}
}
推荐文章
- Manifest合并失败:uses-sdk:minSdkVersion 14
- 为什么Android工作室说“等待调试器”如果我不调试?
- 如何检查我的EditText字段是否为空?
- Android从图库中选择图像
- 后台任务,进度对话框,方向改变-有任何100%工作的解决方案吗?
- Android:垂直对齐多行EditText(文本区域)
- Android无尽列表
- Android room persistent: AppDatabase_Impl不存在
- 错误:执行失败的任务':app:compileDebugKotlin'。>编译错误。详细信息请参见日志
- 在Android中使用URI生成器或使用变量创建URL
- 缩放图像以填充ImageView宽度并保持纵横比
- 列表视图的自定义适配器
- 在Android中设置TextView span的颜色
- 如何以编程方式在RelativeLayout中布局视图?
- Android Facebook集成无效键散列