在 node 中我们会使用,require('os')
但我们不能在 react native 上做这样的事情。有任何想法吗?
如何在 React Native 上获取设备的 ip?
IT技术
reactjs
react-native
2021-05-06 21:33:32
4个回答
有一个 ReactNative 库用于获取有关设备网络的信息:
// 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.'
});
这个包提供了以下 apis
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
这个有更多的功能,看起来有一个更大的社区在使用它。
其它你可能感兴趣的问题