├── .gitignore ├── LICENSE ├── README.md ├── app ├── .gitignore ├── build.gradle ├── proguard-rules.pro └── src │ └── main │ ├── AndroidManifest.xml │ ├── java │ └── com │ │ └── sohu │ │ └── ping │ │ ├── MainActivity.java │ │ ├── NativeMethodHelper.java │ │ └── utils │ │ ├── DnsLookup.java │ │ └── LogUtils.java │ ├── jni │ ├── Android.mk │ ├── native_jni.c │ ├── native_jni.h │ ├── ping.c │ ├── ping.h │ ├── utils.c │ └── utils.h │ └── res │ ├── drawable-v24 │ └── ic_launcher_foreground.xml │ ├── drawable │ └── ic_launcher_background.xml │ ├── layout │ └── activity_main.xml │ ├── mipmap-anydpi-v26 │ ├── ic_launcher.xml │ └── ic_launcher_round.xml │ ├── mipmap-hdpi │ ├── ic_launcher.png │ └── ic_launcher_round.png │ ├── mipmap-mdpi │ ├── ic_launcher.png │ └── ic_launcher_round.png │ ├── mipmap-xhdpi │ ├── ic_launcher.png │ └── ic_launcher_round.png │ ├── mipmap-xxhdpi │ ├── ic_launcher.png │ └── ic_launcher_round.png │ ├── mipmap-xxxhdpi │ ├── ic_launcher.png │ └── ic_launcher_round.png │ └── values │ ├── colors.xml │ ├── strings.xml │ └── styles.xml ├── build.gradle ├── gradle.properties ├── gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── gradlew ├── gradlew.bat └── settings.gradle /.gitignore: -------------------------------------------------------------------------------- 1 | # Created by https://www.gitignore.io 2 | 3 | ### Gradle include folders and files ### 4 | .gradle 5 | 6 | # Ignore Gradle GUI config 7 | gradle-app.setting 8 | 9 | # Avoid ignoring Gradle wrapper jar file (.jar files are usually ignored) 10 | !gradle-wrapper.jar 11 | 12 | ### Android ### 13 | # Built application files 14 | sohuVideoMobile/*.apk 15 | buildtools/*.apk 16 | *.ap_ 17 | */**/multidexconfig.json 18 | # Files for the Dalvik VM 19 | *.dex 20 | 21 | # Java class files 22 | *.class 23 | 24 | # Generated files 25 | bin/ 26 | gen/ 27 | 28 | # Gradle files 29 | build 30 | 31 | 32 | # Local configuration file (sdk path, etc) 33 | #local.properties 34 | 35 | # Proguard folder generated by Eclipse 36 | proguard/ 37 | 38 | # Log Files 39 | *.log 40 | 41 | ### Android Patch ### 42 | gen-external-apklibs 43 | 44 | # idea 45 | .idea 46 | 47 | #local.properties 48 | local.properties 49 | 50 | *.iml 51 | 52 | # original file saved after performing a merge in git 53 | *.orig 54 | 55 | buildtools/mapping.txt 56 | buildtools/seeds.txt 57 | buildtools/usage.txt 58 | .DS_Store 59 | 60 | ### Android freeline files2 ### 61 | freeline/ 62 | freeline_core 63 | freeline.py 64 | freeline_project_description.json 65 | 66 | rocoofix/ 67 | Users/ 68 | *.local_bak 69 | 70 | app/.externalNativeBuild 71 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # PingForAndroid 2 | > C库采用SOCK_DGRAM方式构建icmp包,避开raw socket必须root权限的限制,实现ping功能。 3 | 4 | ## ping实现方式 5 | ### 1. 通常实现方式 6 | 这种方式是直接创建网络层的socket,可以自己构建ip包,也可以委托系统填充。好处是返回的数据包也包括ip数据包,可以获取ttl数据,但是创建raw socket需要拥有root权限这也限制了不能在android上面采用。 7 | 8 | ```java 9 | socket(AF_INET, SOCK_RAW, IPPROTO_ICMP); 10 | ``` 11 | 12 | ### 2. 避过root权限限制解决方案 13 | 这种方式采用DGRAM方式创建socket,不会被root权限所限制,缺点是返回的数据包不包含ip包数据,无法获取ttl数据。经过测试可以在Android平台通过jni使用,可以满足基本需求。 14 | 15 | ```java 16 | socket(AF_INET, SOCK_DGRAM, IPPROTO_ICMP); 17 | ``` 18 | 采用这种方式利用了ICMP协议的特性,数据部分不会被修改,会原样返回,所以可以填充发送时间和自己计算首部的校验和来验证自己发送的包; 19 | 20 | ```java 21 | typedef struct _TAG_ICMP_PACKET 22 | { 23 | ICMP_HEADER icmp_header; //icmp头部,需要根据icmp协议构建 24 | struct timeval icmp_time; //自己填充发送时间,用于计算往返时间 25 | u_int16_t icmp_sum_flag; //自己填充校验和,验证是否是自己发送的ICMP包 26 | u_int8_t imcp_data[DATA_SIZE]; //其它数据,直接填充0 27 | } ICMP_PACKET; 28 | ``` 29 | 经过验证,在mac上面还是可以收到ip首部,移植到android平台就不会收到ip头的数据;所以还是添加了对ip首部的处理逻辑,自己的校验和也添加上,可以在mac平台正常使用。 30 | 31 | > 如果对您有用的话麻烦star支持一下~非常感谢 -------------------------------------------------------------------------------- /app/.gitignore: -------------------------------------------------------------------------------- 1 | /build 2 | -------------------------------------------------------------------------------- /app/build.gradle: -------------------------------------------------------------------------------- 1 | apply plugin: 'com.android.application' 2 | 3 | android { 4 | compileSdkVersion 28 5 | defaultConfig { 6 | applicationId "com.sohu.ping" 7 | minSdkVersion 14 8 | targetSdkVersion 28 9 | versionCode 1 10 | versionName "1.0" 11 | testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner" 12 | 13 | ndk { 14 | abiFilters("armeabi-v7a", "arm64-v8a", "x86", "x86_64") 15 | } 16 | } 17 | buildTypes { 18 | release { 19 | minifyEnabled false 20 | proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' 21 | } 22 | } 23 | 24 | externalNativeBuild { 25 | ndkBuild { 26 | path "src/main/jni/Android.mk" 27 | } 28 | } 29 | } 30 | 31 | dependencies { 32 | implementation fileTree(dir: 'libs', include: ['*.jar']) 33 | implementation 'com.android.support:appcompat-v7:28.0.0' 34 | implementation 'com.android.support.constraint:constraint-layout:1.1.3' 35 | testImplementation 'junit:junit:4.12' 36 | androidTestImplementation 'com.android.support.test:runner:1.0.2' 37 | androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2' 38 | } 39 | -------------------------------------------------------------------------------- /app/proguard-rules.pro: -------------------------------------------------------------------------------- 1 | # Add project specific ProGuard rules here. 2 | # You can control the set of applied configuration files using the 3 | # proguardFiles setting in build.gradle. 4 | # 5 | # For more details, see 6 | # http://developer.android.com/guide/developing/tools/proguard.html 7 | 8 | # If your project uses WebView with JS, uncomment the following 9 | # and specify the fully qualified class name to the JavaScript interface 10 | # class: 11 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview { 12 | # public *; 13 | #} 14 | 15 | # Uncomment this to preserve the line number information for 16 | # debugging stack traces. 17 | #-keepattributes SourceFile,LineNumberTable 18 | 19 | # If you keep the line number information, uncomment this to 20 | # hide the original source file name. 21 | #-renamesourcefileattribute SourceFile 22 | -------------------------------------------------------------------------------- /app/src/main/AndroidManifest.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | -------------------------------------------------------------------------------- /app/src/main/java/com/sohu/ping/MainActivity.java: -------------------------------------------------------------------------------- 1 | package com.sohu.ping; 2 | 3 | import android.os.Handler; 4 | import android.os.Looper; 5 | import android.os.Message; 6 | import android.support.v7.app.AppCompatActivity; 7 | import android.os.Bundle; 8 | import android.view.View; 9 | import android.widget.Button; 10 | import android.widget.EditText; 11 | import android.widget.TextView; 12 | 13 | import com.sohu.ping.utils.DnsLookup; 14 | import com.sohu.ping.utils.LogUtils; 15 | 16 | public class MainActivity extends AppCompatActivity { 17 | 18 | private final String TAG = "MainActivity"; 19 | private Button ping; 20 | private Button dns_ping; 21 | private TextView text; 22 | private EditText domain_edit; 23 | 24 | private final byte PING_RESUT = 0x01; 25 | 26 | @Override 27 | protected void onCreate(Bundle savedInstanceState) { 28 | super.onCreate(savedInstanceState); 29 | setContentView(R.layout.activity_main); 30 | initView(); 31 | initListener(); 32 | } 33 | 34 | private void initView() { 35 | ping = (Button) findViewById(R.id.ping); 36 | dns_ping = (Button) findViewById(R.id.dns_ping); 37 | text = (TextView) findViewById(R.id.text); 38 | domain_edit = (EditText) findViewById(R.id.domain); 39 | } 40 | 41 | private void initListener() { 42 | ping.setOnClickListener(listener); 43 | dns_ping.setOnClickListener(listener); 44 | } 45 | 46 | private View.OnClickListener listener = new View.OnClickListener() { 47 | @Override 48 | public void onClick(View v) { 49 | switch (v.getId()) { 50 | case R.id.ping: 51 | text.setText(""); 52 | new Thread(new Runnable() { 53 | @Override 54 | public void run() { 55 | String res = NativeMethodHelper.ping(domain_edit.getText().toString()); 56 | showResult(res); 57 | } 58 | }).start(); 59 | break; 60 | case R.id.dns_ping: 61 | text.setText(""); 62 | new Thread(new Runnable() { 63 | @Override 64 | public void run() { 65 | String ip = DnsLookup.resolveHostToIp(domain_edit.getText().toString(), 3000); 66 | if (ip != null) { 67 | String res = NativeMethodHelper.ping(ip); 68 | showResult(res); 69 | } else { 70 | LogUtils.d(TAG, "dns resolve error."); 71 | } 72 | } 73 | }).start(); 74 | break; 75 | } 76 | } 77 | }; 78 | 79 | private void showResult(String result) { 80 | Message msg = handler.obtainMessage(); 81 | msg.what = PING_RESUT; 82 | msg.obj = result; 83 | handler.sendMessage(msg); 84 | } 85 | 86 | private Handler handler = new Handler(Looper.getMainLooper(), new Handler.Callback() { 87 | @Override 88 | public boolean handleMessage(Message msg) { 89 | switch (msg.what) { 90 | case PING_RESUT: 91 | text.setText((String)msg.obj); 92 | break; 93 | } 94 | 95 | return false; 96 | } 97 | }); 98 | } 99 | -------------------------------------------------------------------------------- /app/src/main/java/com/sohu/ping/NativeMethodHelper.java: -------------------------------------------------------------------------------- 1 | package com.sohu.ping; 2 | 3 | /** 4 | * Created by wangyan on 2019/3/14 5 | */ 6 | public class NativeMethodHelper { 7 | 8 | static { 9 | System.loadLibrary("native"); 10 | } 11 | 12 | public static native String ping(String domain); 13 | } 14 | -------------------------------------------------------------------------------- /app/src/main/java/com/sohu/ping/utils/DnsLookup.java: -------------------------------------------------------------------------------- 1 | package com.sohu.ping.utils; 2 | 3 | import java.net.InetAddress; 4 | import java.net.UnknownHostException; 5 | 6 | /** 7 | * Created by wangyan on 2019/3/20 8 | */ 9 | public class DnsLookup { 10 | 11 | private static final String TAG = "DnsLookup"; 12 | 13 | public static String resolveHostToIp(String host, long timeout) { 14 | try { 15 | DnsRunnable dnsRunnable = new DnsRunnable(host); 16 | Thread thread = new Thread(dnsRunnable); 17 | thread.start(); 18 | thread.join(timeout); 19 | return dnsRunnable.getIP(); 20 | } catch (InterruptedException e) { 21 | LogUtils.e(TAG, e); 22 | } catch (Exception e) { 23 | LogUtils.e(TAG, e); 24 | } 25 | 26 | return null; 27 | } 28 | 29 | 30 | private static class DnsRunnable implements Runnable { 31 | private InetAddress addr; 32 | private String hostname; 33 | 34 | private DnsRunnable(String hostname) { 35 | this.hostname = hostname; 36 | } 37 | 38 | @Override 39 | public void run() { 40 | long startTime = System.currentTimeMillis(); 41 | try { 42 | InetAddress add = InetAddress.getByName(hostname); 43 | set(add); 44 | } catch (UnknownHostException e) { 45 | LogUtils.e(TAG, e); 46 | } 47 | 48 | LogUtils.d(TAG, hostname + " cost time: " + (System.currentTimeMillis() - startTime)); 49 | } 50 | 51 | private synchronized void set(InetAddress addr) { 52 | this.addr = addr; 53 | } 54 | 55 | private synchronized String getIP() { 56 | if (null != this.addr) { 57 | return addr.getHostAddress(); 58 | } 59 | 60 | return null; 61 | } 62 | } 63 | } 64 | -------------------------------------------------------------------------------- /app/src/main/java/com/sohu/ping/utils/LogUtils.java: -------------------------------------------------------------------------------- 1 | package com.sohu.ping.utils; 2 | 3 | import android.util.Log; 4 | 5 | /** 6 | * Created by wangyan on 2019/3/20 7 | */ 8 | public class LogUtils { 9 | private static boolean isShowLog = true; 10 | private static final String DEFAULT_TAG = "ping"; 11 | 12 | public static void i(String tag, String message) { 13 | if (isShowLog) { 14 | Log.i(DEFAULT_TAG, tag + " [" + message + "]"); 15 | } 16 | } 17 | 18 | public static void i(String message) { 19 | if (isShowLog) { 20 | Log.i(DEFAULT_TAG, message); 21 | } 22 | } 23 | 24 | public static void d(String tag, String message) { 25 | if (isShowLog) { 26 | Log.d(DEFAULT_TAG, tag + " [" + message + "]"); 27 | } 28 | } 29 | 30 | public static void d(String message) { 31 | if (isShowLog) { 32 | Log.d(DEFAULT_TAG, message); 33 | } 34 | } 35 | 36 | public static void w(String tag, String message) { 37 | if (isShowLog) { 38 | Log.w(DEFAULT_TAG, tag + " [" + message + "]"); 39 | } 40 | } 41 | 42 | public static void w(String message) { 43 | if (isShowLog) { 44 | Log.w(DEFAULT_TAG, message); 45 | } 46 | } 47 | 48 | public static void e(String tag, String message, Throwable e) { 49 | if (isShowLog) { 50 | Log.e(DEFAULT_TAG, tag + " [" + message + "]", e); 51 | } 52 | } 53 | 54 | public static void e(String tag, Throwable e) { 55 | if (isShowLog) { 56 | Log.e(DEFAULT_TAG, tag + " [" + Log.getStackTraceString(e) + "]", e); 57 | } 58 | } 59 | 60 | public static void setDebug(boolean isDebug) { 61 | isShowLog = isDebug; 62 | } 63 | 64 | public static boolean isDebug() { 65 | return isShowLog; 66 | } 67 | } 68 | -------------------------------------------------------------------------------- /app/src/main/jni/Android.mk: -------------------------------------------------------------------------------- 1 | LOCAL_PATH := $(call my-dir) 2 | 3 | include $(CLEAR_VARS) 4 | 5 | LOCAL_MODULE := native 6 | LOCAL_SRC_FILES := native_jni.c ping.c utils.c 7 | 8 | # for logging 9 | #LOCAL_C_INCLUDES := $(LOCAL_PATH)/httping 10 | #VERSION := 1.0 11 | #LOCAL_CFLAGS += -DNO_SSL -DVERSION=\"$(VERSION)\" 12 | LOCAL_LDLIBS += -llog -lm 13 | 14 | include $(BUILD_SHARED_LIBRARY) 15 | -------------------------------------------------------------------------------- /app/src/main/jni/native_jni.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | #include "ping.h" 6 | #include "utils.h" 7 | #include "native_jni.h" 8 | 9 | #define PING_RES_BUFFER_LEN 1024 10 | 11 | /* 12 | * Class: com_sohu_opengl_NativeMethodHelper 13 | * Method: ping 14 | * Signature: (Ljava/lang/String;)I 15 | */ 16 | JNIEXPORT jstring JNICALL Java_com_sohu_ping_NativeMethodHelper_ping 17 | (JNIEnv *env, jclass nclass, jstring nstring) 18 | { 19 | char * domain = NULL; 20 | char res_buffer[PING_RES_BUFFER_LEN]; 21 | 22 | domain = jstringToChar(env, nstring); 23 | if (domain == NULL) 24 | { 25 | pri_error("convert string error.\n"); 26 | return NULL; 27 | } 28 | 29 | pri_debug("convert string: %s\n", domain); 30 | memset(res_buffer, 0, PING_RES_BUFFER_LEN); 31 | 32 | get_ping_result(domain, 4, res_buffer, PING_RES_BUFFER_LEN); 33 | if (domain != NULL) 34 | { 35 | free(domain); 36 | domain = NULL; 37 | } 38 | 39 | pri_debug("%s\n", res_buffer); 40 | return charTojstring(env, res_buffer); 41 | } -------------------------------------------------------------------------------- /app/src/main/jni/native_jni.h: -------------------------------------------------------------------------------- 1 | /* DO NOT EDIT THIS FILE - it is machine generated */ 2 | #include 3 | /* Header for class com_sohu_opengl_NativeMethodHelper */ 4 | 5 | #ifndef _Included_com_sohu_opengl_NativeMethodHelper 6 | #define _Included_com_sohu_opengl_NativeMethodHelper 7 | #ifdef __cplusplus 8 | extern "C" { 9 | #endif 10 | 11 | /* 12 | * Class: com_sohu_opengl_NativeMethodHelper 13 | * Method: ping 14 | * Signature: (Ljava/lang/String;)I 15 | */ 16 | JNIEXPORT jstring JNICALL Java_com_sohu_ping_NativeMethodHelper_ping 17 | (JNIEnv *, jclass, jstring); 18 | 19 | #ifdef __cplusplus 20 | } 21 | #endif 22 | #endif 23 | -------------------------------------------------------------------------------- /app/src/main/jni/ping.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | #include 7 | #include 8 | #include 9 | #include 10 | #include 11 | #include 12 | #include 13 | #include 14 | 15 | #include "utils.h" 16 | #include "ping.h" 17 | 18 | #define DATA_SIZE 32 19 | #define MAX_RECV_SIZE 1024 20 | 21 | typedef struct _TAG_IP_HEADER 22 | { 23 | u_int8_t ip_head_verlen; 24 | u_int8_t ip_tos; 25 | u_int16_t ip_length; 26 | u_int16_t ip_id; 27 | u_int16_t ip_flags; 28 | u_int8_t ip_ttl; 29 | u_int8_t ip_protacol; 30 | u_int16_t ip_checksum; 31 | u_int32_t ip_source; 32 | u_int32_t ip_destination; 33 | } IP_HEADER; 34 | 35 | typedef struct _TAG_IMCP_HEADER 36 | { 37 | u_int8_t icmp_type; 38 | u_int8_t icmp_code; 39 | u_int16_t check_sum; 40 | u_int16_t icmp_id; 41 | u_int16_t icmp_seq; 42 | } ICMP_HEADER; 43 | 44 | typedef struct _TAG_ICMP_PACKET 45 | { 46 | ICMP_HEADER icmp_header; 47 | struct timeval icmp_time; 48 | u_int16_t icmp_sum_flag; 49 | u_int8_t imcp_data[DATA_SIZE]; 50 | } ICMP_PACKET; 51 | 52 | typedef struct _TAG_THREAD_DATA 53 | { 54 | int fd; 55 | u_int32_t times; 56 | ICMP_PACKET * icmp_packet; 57 | char * buffer; 58 | u_int32_t buffer_len; 59 | struct sockaddr_in * sockaddr; 60 | u_int8_t send_flag; 61 | } THREAD_DATA; 62 | 63 | static u_int16_t generation_checksum(u_int16_t * buf, u_int32_t size); 64 | static double get_time_interval(struct timeval * start, struct timeval * end); 65 | 66 | u_int16_t generation_checksum(u_int16_t * buf, u_int32_t size) 67 | { 68 | u_int64_t cksum = 0; 69 | while(size > 1) 70 | { 71 | cksum += *buf++; 72 | size -= sizeof(u_int16_t); 73 | } 74 | 75 | if(size) 76 | { 77 | cksum += *buf++; 78 | } 79 | 80 | cksum = (cksum>>16) + (cksum & 0xffff); 81 | cksum += (cksum>>16); 82 | 83 | return (u_int16_t)(~cksum); 84 | } 85 | 86 | static double get_time_interval(struct timeval * start, struct timeval * end) 87 | { 88 | double interval; 89 | struct timeval tp; 90 | 91 | tp.tv_sec = end->tv_sec - start->tv_sec; 92 | tp.tv_usec = end->tv_usec - start->tv_usec; 93 | if(tp.tv_usec < 0) 94 | { 95 | tp.tv_sec -= 1; 96 | tp.tv_usec += 1000000; 97 | } 98 | 99 | interval = tp.tv_sec * 1000 + tp.tv_usec * 0.001; 100 | return interval; 101 | } 102 | 103 | static void * send_imcp(void *arg) 104 | { 105 | u_int8_t *flag = NULL; 106 | int times = -1; 107 | int fd = -1; 108 | char * buffer = NULL; 109 | struct sockaddr_in * dest_socket_addr; 110 | ICMP_HEADER *icmp_header = NULL; 111 | ICMP_PACKET *icmp_packet = NULL; 112 | 113 | THREAD_DATA *thread_data = (THREAD_DATA *)arg; 114 | if (thread_data == NULL) 115 | { 116 | return NULL; 117 | } 118 | 119 | dest_socket_addr = thread_data->sockaddr; 120 | if (dest_socket_addr == NULL) 121 | { 122 | return NULL; 123 | } 124 | 125 | flag = &thread_data->send_flag; 126 | if (flag == NULL) 127 | { 128 | return NULL; 129 | } 130 | 131 | times = thread_data->times; 132 | fd = thread_data->fd; 133 | if (fd <= 0) 134 | { 135 | return NULL; 136 | } 137 | 138 | icmp_packet = thread_data->icmp_packet; 139 | if (icmp_packet == NULL) 140 | { 141 | return NULL; 142 | } 143 | 144 | icmp_header = &(icmp_packet->icmp_header); 145 | if (icmp_header == NULL) 146 | { 147 | return NULL; 148 | } 149 | 150 | for (int i = 0; i < thread_data->times; i++) 151 | { 152 | long result = -1; 153 | icmp_header->icmp_seq = htons(i); 154 | icmp_header->check_sum = 0; 155 | 156 | //pri_debug("send packet. %s\n", inet_ntoa(*((struct in_addr*)&(dest_socket_addr->sin_addr.s_addr)))); 157 | gettimeofday(&icmp_packet->icmp_time, NULL); 158 | icmp_packet->icmp_sum_flag = 0; 159 | icmp_header->check_sum = generation_checksum((u_int16_t *) icmp_packet, sizeof(ICMP_PACKET)); 160 | //pri_debug("send sum: %x\n", icmp_header->check_sum); 161 | result = sendto(fd, icmp_packet, sizeof(ICMP_PACKET), 0, (struct sockaddr *)dest_socket_addr, 162 | sizeof(struct sockaddr_in)); 163 | if (result == -1) 164 | { 165 | pri_error("PING: sendto: Network is unreachable\n"); 166 | continue; 167 | } 168 | 169 | sleep(1); 170 | } 171 | 172 | *flag = 0; 173 | return NULL; 174 | } 175 | 176 | static void * recv_imcp(void *arg) 177 | { 178 | u_int8_t *flag = NULL; 179 | int times = -1; 180 | int fd = -1; 181 | char * buffer = NULL; 182 | ICMP_HEADER *icmp_header = NULL; 183 | ICMP_PACKET *icmp_packet = NULL; 184 | 185 | THREAD_DATA *thread_data = (THREAD_DATA *)arg; 186 | if (thread_data == NULL) 187 | { 188 | return NULL; 189 | } 190 | 191 | flag = &thread_data->send_flag; 192 | if (flag == NULL) 193 | { 194 | return NULL; 195 | } 196 | 197 | times = thread_data->times; 198 | fd = thread_data->fd; 199 | if (fd <= 0) 200 | { 201 | return NULL; 202 | } 203 | 204 | icmp_packet = thread_data->icmp_packet; 205 | if (icmp_packet == NULL) 206 | { 207 | return NULL; 208 | } 209 | 210 | icmp_header = &(icmp_packet->icmp_header); 211 | if (icmp_header == NULL) 212 | { 213 | return NULL; 214 | } 215 | 216 | struct sockaddr_in from; 217 | socklen_t from_packet_len; 218 | long read_length; 219 | char recv_buf[MAX_RECV_SIZE]; 220 | struct timeval end; 221 | 222 | from_packet_len = sizeof(struct sockaddr_in); 223 | for (int index = 0; index < times && *flag == 1;) 224 | { 225 | read_length = recvfrom(fd, recv_buf, MAX_RECV_SIZE, 0, 226 | (struct sockaddr*)&from, &from_packet_len); 227 | gettimeofday( &end, NULL ); 228 | if(read_length != -1) 229 | { 230 | IP_HEADER * recv_ip_header = (IP_HEADER*)recv_buf; 231 | int ip_ttl = (int)recv_ip_header->ip_ttl; 232 | ICMP_PACKET * recv_icmp = (ICMP_PACKET *)(recv_buf + 233 | (recv_ip_header->ip_head_verlen & 0x0F) * 4); 234 | //icmp_header * recv_icmp_header = (icmp_header *)(recv_buf + 235 | // (recv_ip_header->ip_head_verlen & 0x0F) * 4); 236 | 237 | //pri_debug("id: %d, seq: %d\n", recv_icmp->icmp_header.icmp_id, recv_icmp->icmp_header.icmp_seq); 238 | if(recv_icmp->icmp_header.icmp_type != 0) 239 | { 240 | pri_error("error type %d received, error code %d \n", recv_icmp->icmp_header.icmp_type, recv_icmp->icmp_header.icmp_code); 241 | continue; 242 | } 243 | 244 | //if(recv_icmp->icmp_header.id != icmp_head->id) 245 | //{ 246 | //pri_error("some else's packet\n"); 247 | //break; 248 | //} 249 | 250 | if (recv_icmp->icmp_sum_flag != icmp_packet->icmp_sum_flag) 251 | { 252 | pri_error("check sum fail.\n"); 253 | continue; 254 | } 255 | 256 | if(read_length >= (0 + sizeof(ICMP_PACKET))) 257 | { 258 | index++; 259 | snprintf(thread_data->buffer, thread_data->buffer_len, "%s%ld bytes from (%s): icmp_seq=%d time=%.2f ms\n", 260 | thread_data->buffer, read_length, inet_ntoa(from.sin_addr), 261 | recv_icmp->icmp_header.icmp_seq / 256, get_time_interval(&recv_icmp->icmp_time, &end)); 262 | 263 | pri_debug("%ld bytes from (%s): icmp_seq=%d ttl=%d time=%.2f ms\n", 264 | read_length, inet_ntoa(from.sin_addr), recv_icmp->icmp_header.icmp_seq / 256, 265 | ip_ttl, get_time_interval(&recv_icmp->icmp_time, &end)); 266 | } 267 | } 268 | else 269 | { 270 | if (errno != EAGAIN) 271 | { 272 | pri_error("receive data error: %s\n", strerror(errno)); 273 | snprintf(thread_data->buffer, thread_data->buffer_len, "receive data error: %s\n", strerror(errno)); 274 | } 275 | } 276 | } 277 | 278 | return NULL; 279 | } 280 | 281 | BOOL get_ping_result(const char * domain, u_int32_t times, char * res_buffer, int buffer_len) 282 | { 283 | int ret = FALSE; 284 | int client_fd = -1; 285 | int size = 50 * MAX_RECV_SIZE; 286 | struct timeval timeout; 287 | 288 | ICMP_PACKET * icmp_packet = NULL; 289 | ICMP_HEADER * icmp_header = NULL; 290 | struct timeval * icmp_send_time = NULL; 291 | 292 | in_addr_t dest_ip; 293 | struct sockaddr_in dest_socket_addr; 294 | 295 | pthread_t send_pid; 296 | pthread_t recv_pid; 297 | 298 | THREAD_DATA thread_data; 299 | 300 | if (res_buffer == NULL || domain == NULL || buffer_len == 0) 301 | { 302 | pri_error("res_buffer: %s, domain: %s, buffer_len: %d\n", res_buffer, domain, buffer_len); 303 | return ret; 304 | } 305 | 306 | dest_ip = inet_addr(domain); 307 | if (dest_ip == INADDR_NONE) 308 | { 309 | struct hostent* p_hostent = gethostbyname(domain); 310 | if(p_hostent) 311 | { 312 | dest_ip = (*(in_addr_t*)p_hostent->h_addr); 313 | } 314 | } 315 | 316 | if (dest_ip == INADDR_NONE) 317 | { 318 | return ret; 319 | } 320 | 321 | client_fd = socket(AF_INET, SOCK_DGRAM, IPPROTO_ICMP); 322 | if (client_fd == -1) 323 | { 324 | pri_error("socket error: %s!\n", strerror(errno)); 325 | return ret; 326 | } 327 | 328 | timeout.tv_sec = 5; 329 | timeout.tv_usec = 0; 330 | setsockopt(client_fd, SOL_SOCKET, SO_RCVBUF, &size, sizeof(size)); 331 | if(setsockopt(client_fd, SOL_SOCKET, SO_RCVTIMEO, &timeout, sizeof(struct timeval))) 332 | { 333 | pri_error("setsocketopt SO_RCVTIMEO error: %s\n", strerror(errno)); 334 | return ret; 335 | } 336 | 337 | if(setsockopt(client_fd, SOL_SOCKET, SO_SNDTIMEO, &timeout, sizeof(struct timeval))) 338 | { 339 | pri_error("setsockopt SO_SNDTIMEO error: %s\n", strerror(errno)); 340 | return ret; 341 | } 342 | 343 | memset(dest_socket_addr.sin_zero, 0, sizeof(dest_socket_addr.sin_zero)); 344 | dest_socket_addr.sin_family = AF_INET; 345 | dest_socket_addr.sin_addr.s_addr = dest_ip; 346 | dest_socket_addr.sin_port = htons(0); 347 | 348 | icmp_packet = (ICMP_PACKET *)malloc(sizeof(ICMP_PACKET)); 349 | if (icmp_packet == NULL) 350 | { 351 | pri_error("malloc error.\n"); 352 | return ret; 353 | } 354 | 355 | memset(icmp_packet, 0, sizeof(ICMP_PACKET)); 356 | 357 | icmp_header = &icmp_packet->icmp_header; 358 | icmp_header->icmp_type = 8; 359 | icmp_header->icmp_code = 0; 360 | icmp_header->icmp_id = getpid(); 361 | 362 | icmp_packet->icmp_sum_flag = generation_checksum((u_int16_t *)icmp_packet, sizeof(ICMP_PACKET)); 363 | pri_debug("PING %s (%s).\n", domain, inet_ntoa(*((struct in_addr*)&dest_ip))); 364 | snprintf(res_buffer, buffer_len, "PING %s (%s).\n", domain, inet_ntoa(*((struct in_addr*)&dest_ip))); 365 | 366 | thread_data.send_flag = 1; 367 | thread_data.sockaddr = &dest_socket_addr; 368 | thread_data.fd = client_fd; 369 | thread_data.buffer = res_buffer; 370 | thread_data.times = times; 371 | thread_data.icmp_packet = icmp_packet; 372 | 373 | ret = pthread_create(&send_pid, NULL, send_imcp, (void *)&thread_data); 374 | if (ret < 0) 375 | { 376 | pri_error("pthread create error: %s\n", strerror(errno)); 377 | goto FAIL_EXIT; 378 | } 379 | 380 | ret = pthread_create(&recv_pid, NULL, recv_imcp, (void *)&thread_data); 381 | if (ret < 0) 382 | { 383 | pri_error("pthread create error: %s\n", strerror(errno)); 384 | pthread_detach(send_pid); 385 | goto FAIL_EXIT; 386 | } 387 | 388 | pthread_join(send_pid, NULL); 389 | pthread_join(recv_pid, NULL); 390 | 391 | FAIL_EXIT: 392 | if (icmp_packet != NULL) 393 | { 394 | free(icmp_packet); 395 | icmp_packet = NULL; 396 | } 397 | 398 | if (client_fd >= 0) 399 | { 400 | close(client_fd); 401 | client_fd = -1; 402 | } 403 | 404 | return ret; 405 | } 406 | 407 | //int ping_host_ip(const char * domain) 408 | //{ 409 | // char buffer[MAX_RECV_SIZE]; 410 | // get_ping_result(domain, buffer, 10); 411 | // 412 | // pri_debug("ping end.\n"); 413 | // return 0; 414 | //} 415 | 416 | #ifndef __ANDROID__ 417 | int main(int argc, char * argv[]) 418 | { 419 | char buffer[MAX_RECV_SIZE]; 420 | BOOL ret = get_ping_result("www.baidu.com", buffer, 10); 421 | 422 | pri_debug("ping result: %d\n", ret); 423 | 424 | return 0; 425 | } 426 | #endif -------------------------------------------------------------------------------- /app/src/main/jni/ping.h: -------------------------------------------------------------------------------- 1 | #ifndef __PING_H__ 2 | #define __PING_H__ 3 | 4 | #ifdef __cplusplus 5 | extern "C"{ 6 | #endif 7 | 8 | #include 9 | 10 | #define BOOL int 11 | #define FALSE -1 12 | #define TRUE 0 13 | 14 | BOOL get_ping_result(const char * domain, u_int32_t times, char * res_buffer, int buffer_len); 15 | 16 | #ifdef __cplusplus 17 | } 18 | #endif 19 | 20 | #endif -------------------------------------------------------------------------------- /app/src/main/jni/utils.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | #include "utils.h" 6 | 7 | char* jstringToChar(JNIEnv *env, jstring jstr) { 8 | char *rtn = NULL; 9 | jclass clsstring = (*env)->FindClass(env, "java/lang/String"); 10 | jstring strencode = (*env)->NewStringUTF(env, "utf-8"); 11 | jmethodID mid = (*env)->GetMethodID(env, clsstring, "getBytes", "(Ljava/lang/String;)[B"); 12 | jbyteArray barr = (jbyteArray) (*env)->CallObjectMethod(env, jstr, mid, strencode); 13 | jsize alen = (*env)->GetArrayLength(env, barr); 14 | jbyte *ba = (*env)->GetByteArrayElements(env, barr, JNI_FALSE); 15 | if (alen > 0) 16 | { 17 | rtn = (char *) malloc(alen + 1); 18 | memcpy(rtn, ba, alen); 19 | rtn[alen] = 0; 20 | } 21 | 22 | (*env)->ReleaseByteArrayElements(env, barr, ba, 0); 23 | return rtn; 24 | } 25 | 26 | jstring charTojstring(JNIEnv* env, const char* str) { 27 | jclass strClass = (*env)->FindClass(env, "java/lang/String"); 28 | jmethodID ctorID = (*env)->GetMethodID(env, strClass, "","([BLjava/lang/String;)V"); 29 | jbyteArray bytes = (*env)->NewByteArray(env, strlen(str)); 30 | (*env)->SetByteArrayRegion(env, bytes, 0, strlen(str), (jbyte *) str); 31 | jstring encoding = (*env)->NewStringUTF(env, "utf-8"); 32 | return (jstring) (*env)->NewObject(env, strClass, ctorID, bytes, encoding); 33 | } -------------------------------------------------------------------------------- /app/src/main/jni/utils.h: -------------------------------------------------------------------------------- 1 | #ifndef __UTILS_H__ 2 | #define __UTILS_H__ 3 | 4 | #include 5 | 6 | #ifdef __ANDROID__ 7 | #include 8 | #include 9 | #define TAG "ping" 10 | #define pri_debug(format, args...) __android_log_print(ANDROID_LOG_DEBUG, TAG, "[%s:%d]" format, basename(__FILE__), __LINE__, ##args) 11 | #define pri_error(format, args...) __android_log_print(ANDROID_LOG_DEBUG, TAG, "[%s:%d]" format, basename(__FILE__), __LINE__, ##args) 12 | 13 | #else 14 | 15 | #define pri_debug(format, args...) printf("[%s:%d]" format, basename(__FILE__), __LINE__, ##args) 16 | #define pri_error(format, args...) printf("[%s:%d]" format, basename(__FILE__), __LINE__, ##args) 17 | 18 | #endif 19 | 20 | #ifdef __cplusplus 21 | extern "C" { 22 | #endif 23 | #ifdef __ANDROID__ 24 | // return需要手动释放 25 | char* jstringToChar(JNIEnv *env, jstring jstr); 26 | jstring charTojstring(JNIEnv* env, const char* str); 27 | #endif 28 | #ifdef __cplusplus 29 | } 30 | #endif 31 | 32 | #endif // __UTILS_H__ 33 | -------------------------------------------------------------------------------- /app/src/main/res/drawable-v24/ic_launcher_foreground.xml: -------------------------------------------------------------------------------- 1 | 7 | 12 | 13 | 19 | 22 | 25 | 26 | 27 | 28 | 34 | 35 | -------------------------------------------------------------------------------- /app/src/main/res/drawable/ic_launcher_background.xml: -------------------------------------------------------------------------------- 1 | 2 | 7 | 10 | 15 | 20 | 25 | 30 | 35 | 40 | 45 | 50 | 55 | 60 | 65 | 70 | 75 | 80 | 85 | 90 | 95 | 100 | 105 | 110 | 115 | 120 | 125 | 130 | 135 | 140 | 145 | 150 | 155 | 160 | 165 | 170 | 171 | -------------------------------------------------------------------------------- /app/src/main/res/layout/activity_main.xml: -------------------------------------------------------------------------------- 1 | 2 | 7 | 8 |