在我的情况下,我需要公共IP地址。但是,在研究了几乎所有与本地IP相关的纪录片,比如:IP地址,我想要的是202.xxx,而不是192.168.xxx。有人能给我点建议吗?
发布于 2020-02-12 05:25:52
据我所知,没有办法从设备内部获取设备的公共IP。这是因为绝大多数时候,设备不知道它是自己的公共IP。公共IP是从ISP分配给设备的,您的设备通常通过任意数量的调制解调器、路由器、交换机等与ISP隔离。
您需要查询一些外部资源或API (如ipify.org),这些资源或API将告诉您公共IP是什么。您可以通过一个简单的HTTP请求来完成这个任务。
import 'package:http/http.dart';
Future<String> getPublicIP() async {
try {
const url = 'https://api.ipify.org';
var response = await http.get(url);
if (response.statusCode == 200) {
// The response body is the IP in plain text, so just
// return it as-is.
return response.body;
} else {
// The request failed with a non-200 code
// The ipify.org API has a lot of guaranteed uptime
// promises, so this shouldn't ever actually happen.
print(response.statusCode);
print(response.body);
return null;
}
} catch (e) {
// Request failed due to an error, most likely because
// the phone isn't connected to the internet.
print(e);
return null;
}
}编辑:现在有一个从Dart包服务获取公共IP信息的IPify。您可以使用此包来代替上面的手动解决方案:
import 'package:dart_ipify/dart_ipify.dart';
void main() async {
final ipv4 = await Ipify.ipv4();
print(ipv4); // 98.207.254.136
final ipv6 = await Ipify.ipv64();
print(ipv6); // 98.207.254.136 or 2a00:1450:400f:80d::200e
final ipv4json = await Ipify.ipv64(format: Format.JSON);
print(ipv4json); //{"ip":"98.207.254.136"} or {"ip":"2a00:1450:400f:80d::200e"}
// The response type can be text, json or jsonp
}发布于 2021-07-26 04:03:28
最近我遇到了一个可以完成这项工作的包dart_ipify。依普化
下面是一个示例:
import 'package:dart_ipify/dart_ipify.dart';
void main() async {
final ipv6 = await Ipify.ipv64();
print(ipv6); // 98.207.254.136 or 2a00:1450:400f:80d::200e
}发布于 2020-09-09 11:46:30
最近我遇到了这个话题。在调查了这个问题之后,我找到了一个使用外部API的解决方案。我正在使用ipstack栈,它有一个慷慨的免费层。
https://stackoverflow.com/questions/60180934
复制相似问题