在Node中我们可以使用require('os')
,但是在React Native上无法这样做。有什么想法吗?
在Node中我们可以使用require('os')
,但是在React Native上无法这样做。有什么想法吗?
有一个React Native库可以获取设备网络信息:
// require module
var NetworkInfo = require('react-native-network-info');
// Get Local IP
NetworkInfo.getIPAddress(ip => {
console.log(ip);
});
import publicIP from 'react-native-public-ip';
publicIP()
.then(ip => {
console.log(ip);
// '47.122.71.234'
})
.catch(error => {
console.log(error);
// 'Unable to get IP address.'
});
了解更多信息请访问: https://www.npmjs.com/package/react-native-public-ip
这个包提供以下API
npm i react-native-network-info
import { NetworkInfo } from "react-native-network-info";
// Get Local IP
NetworkInfo.getIPAddress().then(ipAddress => {
console.log(ipAddress);
});
// Get IPv4 IP (priority: WiFi first, cellular second)
NetworkInfo.getIPV4Address().then(ipv4Address => {
console.log(ipv4Address);
});
// Get Broadcast
NetworkInfo.getBroadcast().then(broadcast => {
console.log(broadcast);
});
// Get SSID
NetworkInfo.getSSID().then(ssid => {
console.log(ssid);
});
// Get BSSID
NetworkInfo.getBSSID().then(bssid => {
console.log(bssid);
});
// Get Subnet
NetworkInfo.getSubnet().then(subnet => {
console.log(subnet);
});
// Get Default Gateway IP
NetworkInfo.getGatewayIPAddress().then(defaultGateway => {
console.log(defaultGateway);
});
// Get frequency (supported only for Android)
NetworkInfo.getFrequency().then(frequency => {
console.log(frequency);
});
只是提供另一个库:https://github.com/react-native-netinfo/react-native-netinfo#netinfostate
这个库具有稍微更多的功能,看起来有更大的社区在使用。
fetch('https://ipapi.co/json/')
.then(response => response.json())
.then(data => {
console.log('ipapi_getIpAddressgetIpAddress', data);
Alert.alert('ipapi', JSON.stringify(data));
}); //paid after some usage
fetch('https://api.ipify.org?format=json')
.then(response => response.json())
.then(data => {
console.log('apiv4_getIpAddressgetIpAddress', data);
Alert.alert('apiv4', JSON.stringify(data));
}); //free
fetch('https://api64.ipify.org?format=json')
.then(response => response.json())
.then(data => {
console.log('apiv6_getIpAddressgetIpAddress', data);
Alert.alert('apiv6', JSON.stringify(data));
}); //free
这是此内容的社区包。 @react-native-community/netinfo
import NetInfo from "@react-native-community/netinfo";
// Subscribe
const unsubscribe = NetInfo.addEventListener(state => {
console.log("Connection type", state.type);
console.log("Is connected?", state.isConnected);
});
// Unsubscribe
unsubscribe();
NetInfo.fetch().then(state => {
console.log("Connection type", state.type);
console.log("Is connected?", state.isConnected);
});
获取公共 IP 地址,请使用以下方法
import publicIP from 'react-native-public-ip';
publicIP()
.then(ip => {
console.log(ip);
// '47.122.71.234'
})
.catch(error => {
console.log(error);
// 'Unable to get IP address.'
});