Android开发获取内网和外网IP地址的工具类
本帖最后由 佚名RJ 于 2021-1-15 09:11 编辑### 1.添加相关权限
```xml
<!-- 拥有完全的网络访问权限 -->
<uses-permission android:name="android.permission.INTERNET" />
<!-- 查看网络连接 -->
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
```
### 2.获取内网和外网IP地址工具类
```java
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.net.URL;
import java.util.Enumeration;
/**
* @Author: yirj
* @Date: 2021/1/14 15:15
* @Remark: Android开发获取内网IP地址和外网IP地址的工具类
*/
public class IpUtils {
/**
* 获取内网IP地址的方法
*
* @return
*/
public static String getIpAddress() {
try {
for (Enumeration<NetworkInterface> enNetI = NetworkInterface.getNetworkInterfaces(); enNetI
.hasMoreElements(); ) {
NetworkInterface netI = enNetI.nextElement();
for (Enumeration<InetAddress> enumIpAddr = netI.getInetAddresses(); enumIpAddr.hasMoreElements(); ) {
InetAddress inetAddress = enumIpAddr.nextElement();
if (inetAddress instanceof Inet4Address && !inetAddress.isLoopbackAddress()) {
String aa = inetAddress.getHostAddress();
// System.out.println("当前内网IP测试:"+aa);
return inetAddress.getHostAddress();
}
}
}
} catch (SocketException e) {
e.printStackTrace();
}
return "";
}
/**
* 获取外网ip地址的方法1--网页信息格式
* @return
*/
public static String getOutNetIP() {
String ipAddress = "";
try {
String address = "http://www.3322.org/dyndns/getip"; //单独只有IP外网地址的API
// String address = "https://ifconfig.co/json"; //json格式信息的API,使用这个自己搞代码
// String address = "http://pv.sohu.com/cityjson?ie=utf-8"; //json格式信息的API,下面有一个使用案例。
URL url = new URL(address);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setUseCaches(false);
connection.setRequestMethod("GET");
connection.setRequestProperty("user-agent", "Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.7 Safari/537.36"); //设置浏览器ua 保证不出现503
if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
InputStream in = connection.getInputStream();
// 将流转化为字符串
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
String tmpString;
StringBuilder retJSON = new StringBuilder();
while ((tmpString = reader.readLine()) != null) {
retJSON.append(tmpString + "\n");
}
ipAddress = retJSON.toString();
// System.out.println("当前外网IP测试:"+ipAddress);
} else {
System.out.println("网络连接异常,无法获取IP地址!");
}
} catch (Exception e) {
}
return ipAddress;
}
/**
* 获取外网ip地址的方法2--Json格式
* @return
*/
public static String GetNetIp() {
URL infoUrl = null;
InputStream inStream = null;
String line = "";
try {
infoUrl = new URL("http://pv.sohu.com/cityjson?ie=utf-8"); //json格式信息的API,使用案例。
URLConnection connection = infoUrl.openConnection();
HttpURLConnection httpConnection = (HttpURLConnection) connection;
int responseCode = httpConnection.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
inStream = httpConnection.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(inStream, "utf-8"));
StringBuilder strber = new StringBuilder();
while ((line = reader.readLine()) != null)
strber.append(line + "\n");
inStream.close();
// 从反馈的结果中提取出IP地址
int start = strber.indexOf("{");
int end = strber.indexOf("}");
String json = strber.substring(start, end + 1);
if (json != null) {
try {
JSONObject jsonObject = new JSONObject(json);
line = jsonObject.optString("cip");
// System.out.println("IP:"+line);
} catch (JSONException e) {
e.printStackTrace();
}
}
return line;
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return line;
}
}
```
### 3.工具类测试及使用
```java
import org.junit.Test;
/**
* @Author: yirj
* @Date: 2021/1/14 15:19
* @Remark: 测试--网页信息格式获取
*/
public class IpUtilsTest {
@Test
public void getOutNetIP() {
String s = IpUtils.getIpAddress();
System.out.println("内网IP地址:" + s);
String s1 = IpUtils.getOutNetIP();
System.out.println("外网IP地址:" + s1);
}
}
```
```java
/**
* @Author: yirj
* @Date: 2021/1/14 15:19
* @Remark: 测试--Json格式(推荐)--可在任意位置随意调用
*/
new Thread(new Runnable() {
@Override
public void run() {
//获取内外网IP地址并输出
String ipAddress = IpUtils.getIpAddress();
String outNetIP = IpUtils.GetNetIp();
System.out.println("内网IP地址:"+ipAddress+" "+"外网IP地址:"+outNetIP);
}
}).start();
```
**上面代码中还有另一个返回JSON格式的API,想深入研究的小伙伴,可以根据那个再试着搞一搞!** 谢谢分享! 感谢分享 感谢分享。虽然有点尴尬,但是我还想说copy就是好。我内网的用的比较多,外网的不怎么用。 谢谢分享 收藏,收藏
页:
[1]