CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-react-native-device-info

Get device information using react-native

Pending
Overview
Eval results
Files

network-connectivity.mddocs/

Network and Connectivity

Network and connectivity information including IP addresses, carrier information, and connection status. Important for network-aware applications and connectivity debugging.

Capabilities

IP Address Information

Get device IP address information.

/**
 * Get IP address (async)
 * @returns Promise resolving to IP address string
 * @platforms Android, iOS, Windows
 */
function getIpAddress(): Promise<string>;

/**
 * Get IP address (sync)
 * @returns IP address string
 * @platforms Android, iOS, Windows
 */
function getIpAddressSync(): string;

Usage Examples:

import { getIpAddress, getIpAddressSync } from 'react-native-device-info';

// Get IP address
const ipAddress = await getIpAddress();
console.log(`IP Address: ${ipAddress}`);

// Sync version for quick access
const ipAddressSync = getIpAddressSync();
console.log(`IP Address (sync): ${ipAddressSync}`);

// IP address validation
const isValidIP = /^(\d{1,3}\.){3}\d{1,3}$/.test(ipAddress);
console.log(`Valid IP: ${isValidIP}`);

// Check if local/private IP
const isPrivateIP = ipAddress.startsWith('192.168.') || 
                   ipAddress.startsWith('10.') || 
                   ipAddress.startsWith('172.');
console.log(`Private IP: ${isPrivateIP}`);

// Network debugging
if (ipAddress === 'unknown' || !isValidIP) {
  console.warn('No network connection or invalid IP');
} else {
  console.log('Network connection available');
}

MAC Address Information

Get device MAC address (limited availability for privacy reasons).

/**
 * Get MAC address (async)
 * @returns Promise resolving to MAC address string
 * @platforms Android (real MAC), iOS (fixed value for privacy)
 */
function getMacAddress(): Promise<string>;

/**
 * Get MAC address (sync)
 * @returns MAC address string
 * @platforms Android (real MAC), iOS (fixed value for privacy)
 */
function getMacAddressSync(): string;

Usage Examples:

import { getMacAddress } from 'react-native-device-info';
import { Platform } from 'react-native';

// Get MAC address
const macAddress = await getMacAddress();
console.log(`MAC Address: ${macAddress}`);

// Platform-specific handling
if (Platform.OS === 'ios') {
  // iOS returns fixed value for privacy: "02:00:00:00:00:00"
  console.log('iOS MAC address is privacy-protected fixed value');
} else if (Platform.OS === 'android') {
  // Android returns actual MAC address (may be restricted in newer versions)
  console.log(`Android MAC address: ${macAddress}`);
  
  // Validate MAC address format
  const isMacValid = /^([0-9A-Fa-f]{2}[:-]){5}([0-9A-Fa-f]{2})$/.test(macAddress);
  console.log(`Valid MAC format: ${isMacValid}`);
}

// Use for device fingerprinting (with privacy considerations)
const deviceFingerprint = {
  macAddress: macAddress,
  platform: Platform.OS,
  isRealMac: Platform.OS === 'android' && macAddress !== 'unknown'
};

Mobile Carrier Information

Get mobile carrier/network operator information.

/**
 * Get mobile carrier name (async)
 * @returns Promise resolving to carrier name string
 * @platforms Android, iOS
 */
function getCarrier(): Promise<string>;

/**
 * Get mobile carrier name (sync)
 * @returns Carrier name string
 * @platforms Android, iOS
 */
function getCarrierSync(): string;

Usage Examples:

import { getCarrier } from 'react-native-device-info';

// Get carrier information
const carrier = await getCarrier();
console.log(`Mobile Carrier: ${carrier}`);

// Carrier-specific features
const knownCarriers = ['Verizon', 'AT&T', 'T-Mobile', 'Sprint'];
const isKnownCarrier = knownCarriers.some(c => 
  carrier.toLowerCase().includes(c.toLowerCase())
);

console.log(`Known carrier: ${isKnownCarrier}`);

// Network optimization based on carrier
switch (carrier.toLowerCase()) {
  case 'verizon':
    console.log('Optimizing for Verizon network');
    break;
  case 'at&t':
    console.log('Optimizing for AT&T network');
    break;
  default:
    console.log('Using default network settings');
}

// Check if device has cellular connectivity
const hasCellular = carrier !== 'unknown' && carrier !== '';
console.log(`Cellular connectivity: ${hasCellular}`);

Airplane Mode Detection

Check if device is in airplane mode.

/**
 * Check if airplane mode is enabled (async)
 * @returns Promise resolving to true if airplane mode is on
 * @platforms Android, Web
 */
function isAirplaneMode(): Promise<boolean>;

/**
 * Check if airplane mode is enabled (sync)
 * @returns True if airplane mode is enabled
 * @platforms Android, Web
 */
function isAirplaneModeSync(): boolean;

Usage Examples:

import { isAirplaneMode } from 'react-native-device-info';

// Check airplane mode
const airplaneMode = await isAirplaneMode();
console.log(`Airplane Mode: ${airplaneMode}`);

// Network-aware functionality
if (airplaneMode) {
  console.log('Airplane mode detected - using offline features only');
  // Switch to offline mode
  // Cache data locally
  // Disable network requests
  // Show offline UI
} else {
  console.log('Network connectivity available');
  // Enable online features
  // Sync data
  // Enable real-time updates
}

// Periodic airplane mode checking
setInterval(async () => {
  const currentAirplaneMode = await isAirplaneMode();
  if (currentAirplaneMode !== airplaneMode) {
    console.log(`Airplane mode changed: ${currentAirplaneMode}`);
    // Handle airplane mode toggle
    if (currentAirplaneMode) {
      // Switched to airplane mode
      console.log('Switching to offline mode');
    } else {
      // Switched off airplane mode
      console.log('Network restored - resuming online features');
    }
  }
}, 5000); // Check every 5 seconds

Location Services Status

Check if location services are enabled.

/**
 * Check if location services are enabled (async)
 * @returns Promise resolving to true if location is enabled
 * @platforms Android, iOS, Web
 */
function isLocationEnabled(): Promise<boolean>;

/**
 * Check if location services are enabled (sync)
 * @returns True if location services are enabled
 * @platforms Android, iOS, Web
 */
function isLocationEnabledSync(): boolean;

/**
 * Get available location providers (async)
 * @returns Promise resolving to location provider info object
 * @platforms Android, iOS
 */
function getAvailableLocationProviders(): Promise<LocationProviderInfo>;

/**
 * Get available location providers (sync)
 * @returns Location provider info object
 * @platforms Android, iOS
 */
function getAvailableLocationProvidersSync(): LocationProviderInfo;

interface LocationProviderInfo {
  [key: string]: boolean;
}

Usage Examples:

import { 
  isLocationEnabled, 
  getAvailableLocationProviders 
} from 'react-native-device-info';

// Check location services
const locationEnabled = await isLocationEnabled();
console.log(`Location Services: ${locationEnabled}`);

// Get available location providers
const locationProviders = await getAvailableLocationProviders();
console.log('Location Providers:', locationProviders);

// Location-based feature availability
if (locationEnabled) {
  console.log('Location-based features available');
  
  // Check specific providers
  if (locationProviders.gps) {
    console.log('GPS provider available - high accuracy location');
  }
  
  if (locationProviders.network) {
    console.log('Network provider available - approximate location');
  }
  
  if (locationProviders.passive) {
    console.log('Passive provider available - battery-efficient location');
  }
} else {
  console.log('Location services disabled - using fallback methods');
  // Disable location features
  // Use IP-based location
  // Prompt user to enable location
}

// Location provider selection
const getBestLocationProvider = (providers: LocationProviderInfo) => {
  if (providers.gps) return 'gps';
  if (providers.network) return 'network';
  if (providers.passive) return 'passive';
  return 'none';
};

const bestProvider = getBestLocationProvider(locationProviders);
console.log(`Best location provider: ${bestProvider}`);

Network Connectivity Utilities

Utility functions for comprehensive network connectivity checking.

Usage Examples:

import { 
  getIpAddress, 
  getMacAddress, 
  getCarrier, 
  isAirplaneMode,
  isLocationEnabled 
} from 'react-native-device-info';

// Network connectivity class
class NetworkConnectivity {
  static async getConnectivityInfo() {
    const [
      ipAddress,
      macAddress,
      carrier,
      airplaneMode,
      locationEnabled
    ] = await Promise.all([
      getIpAddress(),
      getMacAddress(),
      getCarrier(),
      isAirplaneMode(),
      isLocationEnabled()
    ]);
    
    return {
      ipAddress,
      macAddress,
      carrier,
      airplaneMode,
      locationEnabled,
      hasIP: ipAddress !== 'unknown' && ipAddress !== '',
      hasCellular: carrier !== 'unknown' && carrier !== '',
      isOnline: !airplaneMode && (ipAddress !== 'unknown' && ipAddress !== '')
    };
  }
  
  static async getNetworkType() {
    const connectivity = await this.getConnectivityInfo();
    
    if (connectivity.airplaneMode) return 'none';
    if (!connectivity.hasIP) return 'offline';
    if (connectivity.hasCellular) return 'cellular';
    return 'wifi'; // Assumption if has IP but no cellular
  }
  
  static async shouldUseHighBandwidthFeatures() {
    const networkType = await this.getNetworkType();
    const connectivity = await this.getConnectivityInfo();
    
    // Conservative approach - only enable for WiFi
    return networkType === 'wifi' && connectivity.isOnline;
  }
  
  static async getRecommendedSettings() {
    const networkType = await this.getNetworkType();
    const shouldUseHighBandwidth = await this.shouldUseHighBandwidthFeatures();
    
    return {
      networkType,
      enableAutoSync: networkType === 'wifi',
      enableHighQualityImages: shouldUseHighBandwidth,
      enableVideoAutoPlay: shouldUseHighBandwidth,
      maxConcurrentDownloads: shouldUseHighBandwidth ? 4 : 1,
      enableBackgroundRefresh: networkType !== 'none' && networkType !== 'offline'
    };
  }
}

// Usage
const connectivity = await NetworkConnectivity.getConnectivityInfo();
console.log('Connectivity Info:', connectivity);

const networkType = await NetworkConnectivity.getNetworkType();
console.log(`Network Type: ${networkType}`);

const settings = await NetworkConnectivity.getRecommendedSettings();
console.log('Recommended Settings:', settings);

// Apply network-aware settings
if (settings.enableAutoSync) {
  console.log('Enabling automatic sync');
} else {
  console.log('Disabling automatic sync to save bandwidth');
}

Network Debugging and Monitoring

Tools for network debugging and monitoring.

Usage Examples:

import { getIpAddress, getCarrier, isAirplaneMode } from 'react-native-device-info';

// Network debug class
class NetworkDebug {
  static async diagnoseConnectivity() {
    const diagnostics = {
      timestamp: new Date().toISOString(),
      ipAddress: await getIpAddress(),
      carrier: await getCarrier(),
      airplaneMode: await isAirplaneMode(),
      platform: Platform.OS
    };
    
    // Analyze connectivity issues
    const issues = [];
    
    if (diagnostics.airplaneMode) {
      issues.push('Airplane mode is enabled');
    }
    
    if (diagnostics.ipAddress === 'unknown') {
      issues.push('No IP address assigned');
    }
    
    if (diagnostics.carrier === 'unknown') {
      issues.push('No mobile carrier detected');
    }
    
    return {
      ...diagnostics,
      issues,
      isHealthy: issues.length === 0
    };
  }
  
  static async logNetworkState() {
    const diagnosis = await this.diagnoseConnectivity();
    
    console.log('Network Diagnosis:', diagnosis);
    
    if (!diagnosis.isHealthy) {
      console.warn('Network issues detected:', diagnosis.issues);
    }
    
    return diagnosis;
  }
}

// Periodic network monitoring
setInterval(async () => {
  const networkState = await NetworkDebug.diagnoseConnectivity();
  if (!networkState.isHealthy) {
    console.log('Network connectivity issues detected');
    // Handle network issues
    // Show offline UI
    // Cache operations for later
  }
}, 30000); // Check every 30 seconds

Types

interface LocationProviderInfo {
  [key: string]: boolean;
}

Install with Tessl CLI

npx tessl i tessl/npm-react-native-device-info

docs

application-information.md

battery-power.md

device-identification.md

hardware-features.md

index.md

memory-storage.md

network-connectivity.md

react-hooks.md

system-information.md

tile.json