0
# Network and Connectivity
1
2
Network and connectivity information including IP addresses, carrier information, and connection status. Important for network-aware applications and connectivity debugging.
3
4
## Capabilities
5
6
### IP Address Information
7
8
Get device IP address information.
9
10
```typescript { .api }
11
/**
12
* Get IP address (async)
13
* @returns Promise resolving to IP address string
14
* @platforms Android, iOS, Windows
15
*/
16
function getIpAddress(): Promise<string>;
17
18
/**
19
* Get IP address (sync)
20
* @returns IP address string
21
* @platforms Android, iOS, Windows
22
*/
23
function getIpAddressSync(): string;
24
```
25
26
**Usage Examples:**
27
28
```typescript
29
import { getIpAddress, getIpAddressSync } from 'react-native-device-info';
30
31
// Get IP address
32
const ipAddress = await getIpAddress();
33
console.log(`IP Address: ${ipAddress}`);
34
35
// Sync version for quick access
36
const ipAddressSync = getIpAddressSync();
37
console.log(`IP Address (sync): ${ipAddressSync}`);
38
39
// IP address validation
40
const isValidIP = /^(\d{1,3}\.){3}\d{1,3}$/.test(ipAddress);
41
console.log(`Valid IP: ${isValidIP}`);
42
43
// Check if local/private IP
44
const isPrivateIP = ipAddress.startsWith('192.168.') ||
45
ipAddress.startsWith('10.') ||
46
ipAddress.startsWith('172.');
47
console.log(`Private IP: ${isPrivateIP}`);
48
49
// Network debugging
50
if (ipAddress === 'unknown' || !isValidIP) {
51
console.warn('No network connection or invalid IP');
52
} else {
53
console.log('Network connection available');
54
}
55
```
56
57
### MAC Address Information
58
59
Get device MAC address (limited availability for privacy reasons).
60
61
```typescript { .api }
62
/**
63
* Get MAC address (async)
64
* @returns Promise resolving to MAC address string
65
* @platforms Android (real MAC), iOS (fixed value for privacy)
66
*/
67
function getMacAddress(): Promise<string>;
68
69
/**
70
* Get MAC address (sync)
71
* @returns MAC address string
72
* @platforms Android (real MAC), iOS (fixed value for privacy)
73
*/
74
function getMacAddressSync(): string;
75
```
76
77
**Usage Examples:**
78
79
```typescript
80
import { getMacAddress } from 'react-native-device-info';
81
import { Platform } from 'react-native';
82
83
// Get MAC address
84
const macAddress = await getMacAddress();
85
console.log(`MAC Address: ${macAddress}`);
86
87
// Platform-specific handling
88
if (Platform.OS === 'ios') {
89
// iOS returns fixed value for privacy: "02:00:00:00:00:00"
90
console.log('iOS MAC address is privacy-protected fixed value');
91
} else if (Platform.OS === 'android') {
92
// Android returns actual MAC address (may be restricted in newer versions)
93
console.log(`Android MAC address: ${macAddress}`);
94
95
// Validate MAC address format
96
const isMacValid = /^([0-9A-Fa-f]{2}[:-]){5}([0-9A-Fa-f]{2})$/.test(macAddress);
97
console.log(`Valid MAC format: ${isMacValid}`);
98
}
99
100
// Use for device fingerprinting (with privacy considerations)
101
const deviceFingerprint = {
102
macAddress: macAddress,
103
platform: Platform.OS,
104
isRealMac: Platform.OS === 'android' && macAddress !== 'unknown'
105
};
106
```
107
108
### Mobile Carrier Information
109
110
Get mobile carrier/network operator information.
111
112
```typescript { .api }
113
/**
114
* Get mobile carrier name (async)
115
* @returns Promise resolving to carrier name string
116
* @platforms Android, iOS
117
*/
118
function getCarrier(): Promise<string>;
119
120
/**
121
* Get mobile carrier name (sync)
122
* @returns Carrier name string
123
* @platforms Android, iOS
124
*/
125
function getCarrierSync(): string;
126
```
127
128
**Usage Examples:**
129
130
```typescript
131
import { getCarrier } from 'react-native-device-info';
132
133
// Get carrier information
134
const carrier = await getCarrier();
135
console.log(`Mobile Carrier: ${carrier}`);
136
137
// Carrier-specific features
138
const knownCarriers = ['Verizon', 'AT&T', 'T-Mobile', 'Sprint'];
139
const isKnownCarrier = knownCarriers.some(c =>
140
carrier.toLowerCase().includes(c.toLowerCase())
141
);
142
143
console.log(`Known carrier: ${isKnownCarrier}`);
144
145
// Network optimization based on carrier
146
switch (carrier.toLowerCase()) {
147
case 'verizon':
148
console.log('Optimizing for Verizon network');
149
break;
150
case 'at&t':
151
console.log('Optimizing for AT&T network');
152
break;
153
default:
154
console.log('Using default network settings');
155
}
156
157
// Check if device has cellular connectivity
158
const hasCellular = carrier !== 'unknown' && carrier !== '';
159
console.log(`Cellular connectivity: ${hasCellular}`);
160
```
161
162
### Airplane Mode Detection
163
164
Check if device is in airplane mode.
165
166
```typescript { .api }
167
/**
168
* Check if airplane mode is enabled (async)
169
* @returns Promise resolving to true if airplane mode is on
170
* @platforms Android, Web
171
*/
172
function isAirplaneMode(): Promise<boolean>;
173
174
/**
175
* Check if airplane mode is enabled (sync)
176
* @returns True if airplane mode is enabled
177
* @platforms Android, Web
178
*/
179
function isAirplaneModeSync(): boolean;
180
```
181
182
**Usage Examples:**
183
184
```typescript
185
import { isAirplaneMode } from 'react-native-device-info';
186
187
// Check airplane mode
188
const airplaneMode = await isAirplaneMode();
189
console.log(`Airplane Mode: ${airplaneMode}`);
190
191
// Network-aware functionality
192
if (airplaneMode) {
193
console.log('Airplane mode detected - using offline features only');
194
// Switch to offline mode
195
// Cache data locally
196
// Disable network requests
197
// Show offline UI
198
} else {
199
console.log('Network connectivity available');
200
// Enable online features
201
// Sync data
202
// Enable real-time updates
203
}
204
205
// Periodic airplane mode checking
206
setInterval(async () => {
207
const currentAirplaneMode = await isAirplaneMode();
208
if (currentAirplaneMode !== airplaneMode) {
209
console.log(`Airplane mode changed: ${currentAirplaneMode}`);
210
// Handle airplane mode toggle
211
if (currentAirplaneMode) {
212
// Switched to airplane mode
213
console.log('Switching to offline mode');
214
} else {
215
// Switched off airplane mode
216
console.log('Network restored - resuming online features');
217
}
218
}
219
}, 5000); // Check every 5 seconds
220
```
221
222
### Location Services Status
223
224
Check if location services are enabled.
225
226
```typescript { .api }
227
/**
228
* Check if location services are enabled (async)
229
* @returns Promise resolving to true if location is enabled
230
* @platforms Android, iOS, Web
231
*/
232
function isLocationEnabled(): Promise<boolean>;
233
234
/**
235
* Check if location services are enabled (sync)
236
* @returns True if location services are enabled
237
* @platforms Android, iOS, Web
238
*/
239
function isLocationEnabledSync(): boolean;
240
241
/**
242
* Get available location providers (async)
243
* @returns Promise resolving to location provider info object
244
* @platforms Android, iOS
245
*/
246
function getAvailableLocationProviders(): Promise<LocationProviderInfo>;
247
248
/**
249
* Get available location providers (sync)
250
* @returns Location provider info object
251
* @platforms Android, iOS
252
*/
253
function getAvailableLocationProvidersSync(): LocationProviderInfo;
254
255
interface LocationProviderInfo {
256
[key: string]: boolean;
257
}
258
```
259
260
**Usage Examples:**
261
262
```typescript
263
import {
264
isLocationEnabled,
265
getAvailableLocationProviders
266
} from 'react-native-device-info';
267
268
// Check location services
269
const locationEnabled = await isLocationEnabled();
270
console.log(`Location Services: ${locationEnabled}`);
271
272
// Get available location providers
273
const locationProviders = await getAvailableLocationProviders();
274
console.log('Location Providers:', locationProviders);
275
276
// Location-based feature availability
277
if (locationEnabled) {
278
console.log('Location-based features available');
279
280
// Check specific providers
281
if (locationProviders.gps) {
282
console.log('GPS provider available - high accuracy location');
283
}
284
285
if (locationProviders.network) {
286
console.log('Network provider available - approximate location');
287
}
288
289
if (locationProviders.passive) {
290
console.log('Passive provider available - battery-efficient location');
291
}
292
} else {
293
console.log('Location services disabled - using fallback methods');
294
// Disable location features
295
// Use IP-based location
296
// Prompt user to enable location
297
}
298
299
// Location provider selection
300
const getBestLocationProvider = (providers: LocationProviderInfo) => {
301
if (providers.gps) return 'gps';
302
if (providers.network) return 'network';
303
if (providers.passive) return 'passive';
304
return 'none';
305
};
306
307
const bestProvider = getBestLocationProvider(locationProviders);
308
console.log(`Best location provider: ${bestProvider}`);
309
```
310
311
### Network Connectivity Utilities
312
313
Utility functions for comprehensive network connectivity checking.
314
315
**Usage Examples:**
316
317
```typescript
318
import {
319
getIpAddress,
320
getMacAddress,
321
getCarrier,
322
isAirplaneMode,
323
isLocationEnabled
324
} from 'react-native-device-info';
325
326
// Network connectivity class
327
class NetworkConnectivity {
328
static async getConnectivityInfo() {
329
const [
330
ipAddress,
331
macAddress,
332
carrier,
333
airplaneMode,
334
locationEnabled
335
] = await Promise.all([
336
getIpAddress(),
337
getMacAddress(),
338
getCarrier(),
339
isAirplaneMode(),
340
isLocationEnabled()
341
]);
342
343
return {
344
ipAddress,
345
macAddress,
346
carrier,
347
airplaneMode,
348
locationEnabled,
349
hasIP: ipAddress !== 'unknown' && ipAddress !== '',
350
hasCellular: carrier !== 'unknown' && carrier !== '',
351
isOnline: !airplaneMode && (ipAddress !== 'unknown' && ipAddress !== '')
352
};
353
}
354
355
static async getNetworkType() {
356
const connectivity = await this.getConnectivityInfo();
357
358
if (connectivity.airplaneMode) return 'none';
359
if (!connectivity.hasIP) return 'offline';
360
if (connectivity.hasCellular) return 'cellular';
361
return 'wifi'; // Assumption if has IP but no cellular
362
}
363
364
static async shouldUseHighBandwidthFeatures() {
365
const networkType = await this.getNetworkType();
366
const connectivity = await this.getConnectivityInfo();
367
368
// Conservative approach - only enable for WiFi
369
return networkType === 'wifi' && connectivity.isOnline;
370
}
371
372
static async getRecommendedSettings() {
373
const networkType = await this.getNetworkType();
374
const shouldUseHighBandwidth = await this.shouldUseHighBandwidthFeatures();
375
376
return {
377
networkType,
378
enableAutoSync: networkType === 'wifi',
379
enableHighQualityImages: shouldUseHighBandwidth,
380
enableVideoAutoPlay: shouldUseHighBandwidth,
381
maxConcurrentDownloads: shouldUseHighBandwidth ? 4 : 1,
382
enableBackgroundRefresh: networkType !== 'none' && networkType !== 'offline'
383
};
384
}
385
}
386
387
// Usage
388
const connectivity = await NetworkConnectivity.getConnectivityInfo();
389
console.log('Connectivity Info:', connectivity);
390
391
const networkType = await NetworkConnectivity.getNetworkType();
392
console.log(`Network Type: ${networkType}`);
393
394
const settings = await NetworkConnectivity.getRecommendedSettings();
395
console.log('Recommended Settings:', settings);
396
397
// Apply network-aware settings
398
if (settings.enableAutoSync) {
399
console.log('Enabling automatic sync');
400
} else {
401
console.log('Disabling automatic sync to save bandwidth');
402
}
403
```
404
405
### Network Debugging and Monitoring
406
407
Tools for network debugging and monitoring.
408
409
**Usage Examples:**
410
411
```typescript
412
import { getIpAddress, getCarrier, isAirplaneMode } from 'react-native-device-info';
413
414
// Network debug class
415
class NetworkDebug {
416
static async diagnoseConnectivity() {
417
const diagnostics = {
418
timestamp: new Date().toISOString(),
419
ipAddress: await getIpAddress(),
420
carrier: await getCarrier(),
421
airplaneMode: await isAirplaneMode(),
422
platform: Platform.OS
423
};
424
425
// Analyze connectivity issues
426
const issues = [];
427
428
if (diagnostics.airplaneMode) {
429
issues.push('Airplane mode is enabled');
430
}
431
432
if (diagnostics.ipAddress === 'unknown') {
433
issues.push('No IP address assigned');
434
}
435
436
if (diagnostics.carrier === 'unknown') {
437
issues.push('No mobile carrier detected');
438
}
439
440
return {
441
...diagnostics,
442
issues,
443
isHealthy: issues.length === 0
444
};
445
}
446
447
static async logNetworkState() {
448
const diagnosis = await this.diagnoseConnectivity();
449
450
console.log('Network Diagnosis:', diagnosis);
451
452
if (!diagnosis.isHealthy) {
453
console.warn('Network issues detected:', diagnosis.issues);
454
}
455
456
return diagnosis;
457
}
458
}
459
460
// Periodic network monitoring
461
setInterval(async () => {
462
const networkState = await NetworkDebug.diagnoseConnectivity();
463
if (!networkState.isHealthy) {
464
console.log('Network connectivity issues detected');
465
// Handle network issues
466
// Show offline UI
467
// Cache operations for later
468
}
469
}, 30000); // Check every 30 seconds
470
```
471
472
## Types
473
474
```typescript { .api }
475
interface LocationProviderInfo {
476
[key: string]: boolean;
477
}
478
```