Ben
Ben

Reputation: 135

How to get IP address of Computer when running React Native app?

I'm trying to build an app which can get IP address of computer when running app. I have found react-native-public-ip but seems like that it gets IP address of the virtual device. So Is there anyway I can get IP address of computer?

Upvotes: 6

Views: 11940

Answers (2)

Akshay Mulgavkar
Akshay Mulgavkar

Reputation: 1748

react-native-network-info is a good option but you can also you react-native-netinfo

Migrating from the core react-native module

This module was created when the NetInfo was split out from the core of React Native. To migrate to this module you need to follow the installation instructions and then change you imports from:

import { NetInfo } from "react-native";

to:

import NetInfo from "@react-native-community/netinfo";

Usage

Import the library:

import NetInfo from "@react-native-community/netinfo";

Get the network state once:

NetInfo.fetch().then(state => {
  console.log("Connection type", state.type);
  console.log("Is connected?", state.isConnected);
});

Subscribe to network state updates:

// Subscribe
const unsubscribe = NetInfo.addEventListener(state => {
  console.log("Connection type", state.type);
  console.log("Is connected?", state.isConnected);
});

// Unsubscribe
unsubscribe();

API

Types:

NetInfoState
NetInfoStateType
NetInfoCellularGeneration

Methods:

fetch()
addEventListener()
useNetInfo()

You're good to go!! Hope this helps.

Upvotes: 2

hong developer
hong developer

Reputation: 13906

React Native library for getting information about the devices network

You can use react-native-network-info

Example.js

import { NetworkInfo } from "react-native-network-info";

// Get Local IP
const ipAddress = await NetworkInfo.getIPAddress();

// Get IPv4 IP
const ipv4Address = await NetworkInfo.getIPV4Address();

// Get Broadcast
const broadcast = await NetworkInfo.getBroadcast();

Upvotes: 1

Related Questions