我最近遇到了一个有线问题。我有一个连接wifi的android设备,我确定wifi很好。但是android设备无法访问互联网。然后我发现DNS解析有问题,这就是我所做的。
1。我编写了一个仅在MainActivity中调用InetAddress.getAllByName("www.google.com")
方法的应用。
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new Thread(new Runnable() {
@Override
public void run() {
try {
Log.d("DNSTEST", "here >>> 0");
InetAddress[] addresses = InetAddress.getAllByName("www.google.com");
Log.d("DNSTEST", "here >>> 1");
if (addresses != null) {
Log.d("DNSTEST", "here >>> 2");
for (InetAddress address : addresses) {
Log.d("DNSTEST", "here >>> 3");
Log.d("DNSTEST", "address: " + address.getHostAddress());
}
}
Log.d("DNSTEST", "here >>> 4");
} catch (UnknownHostException e) {
e.printStackTrace();
}
}
}).start();
}
这是logcat的输出:
2019-05-27 11:14:36.710 5204-5221/com.upward.dns D/DNSTEST: here >>> 0
如您所见,执行InetAddress.getAllByName("www.google.com")
时它被阻止。
2。然后,我使用C ++编写了一个可执行程序,尝试查看直接在android上执行时是否被阻止。
/*
* dns.cpp
*
* Created on: May 27, 2019
* Author: Will Tang
*/
#include<cstdio>
#include<netdb.h>
#include<arpa/inet.h>
int main()
{
printf("here >>> 0\n");
struct hostent *hptr = gethostbyname("www.google.com");
printf("here >>> 1\n");
char** pptr = hptr->h_addr_list;
printf("here >>> 2\n");
char str[32] = {0};
printf("here >>> 3\n");
for (; *pptr != nullptr; pptr++) {
printf("here >>> 4\n");
printf("address: %s\n", inet_ntop(hptr->h_addrtype, *pptr, str, sizeof(str)));
}
printf("done\n");
}
将源代码添加到可执行程序“ DNS”中,然后将其推送到android SD卡目录中,然后执行它。
没关系!
3。然后,我用相同的C ++代码编写了一个共享库,并使用JNI让Java调用C ++代码。
#include "com_upward_dns_DNSTest.h"
#include <android/log.h>
#include <thread>
#include <netdb.h>
#include <arpa/inet.h>
#define TAG "DNSTEST"
#define printf(...) __android_log_print(ANDROID_LOG_DEBUG, TAG, __VA_ARGS__)
JNIEXPORT void JNICALL Java_com_upward_dns_DNSTest_test(JNIEnv *env, jobject obj, jint count)
{
printf("here >>> 0");
struct hostent *hptr = gethostbyname("www.google.com");
printf("here >>> 1");
char** pptr = hptr->h_addr_list;
printf("here >>> 2");
char str[32] = {0};
printf("here >>> 3");
for (; *pptr != nullptr; pptr++) {
printf("here >>> 4");
printf("address: %s\n", inet_ntop(hptr->h_addrtype, *pptr, str, sizeof(str)));
}
printf("done");
}
package com.upward.dns;
public class DNSTest {
static {
System.loadLibrary("dns");
}
public native void test();
}
2019-05-27 11:41:18.694 5860-5860/com.upward.dns D/DNSTEST_JNI: here >>> 0
坏消息,它被阻止了。谁能给我一些建议?谢谢!