如何在React Native上获取设备的ip?

时间:2016-07-26 16:29:41

标签: reactjs react-native

在节点中我们会使用require('os')但我们不能做出反应原生的事情。有什么想法吗?

3 个答案:

答案 0 :(得分:11)

有一个ReactNative库,用于获取有关设备网络的信息:

react-native-network-info

// require module
var NetworkInfo = require('react-native-network-info');

// Get Local IP
NetworkInfo.getIPAddress(ip => {
  console.log(ip);
});

答案 1 :(得分:3)

此软件包提供了以下API

function startTime() {
    var today = new Date();
    var h = today.getHours();
    var m = today.getMinutes();
    var s = today.getSeconds();
    var y = today.getFullYear();
    var o = today.getMonth();
    var a = today.getDate();
    var d = today.getDay();

    var monthnames = new Array();
    monthnames[0] = "January";
    monthnames[1] = "February";
    monthnames[2] = "March";
    monthnames[3] = "April";
    monthnames[4] = "May";
    monthnames[5] = "June";
    monthnames[6] = "July";
    monthnames[7] = "August";
    monthnames[8] = "September";
    monthnames[9] = "Oktober";
    monthnames[10] = "November";
    monthnames[11] = "December";

    var weekdays = new Array();
    weekdays[0] = "Sunday";
    weekdays[1] = "Monday";
    weekdays[2] = "Tuesday";
    weekdays[3] = "Wednesday";
    weekdays[4] = "Thursday";
    weekdays[5] = "Friday";
    weekdays[6] = "Saturday";

    m = checkTime(m);
    s = checkTime(s);
    a = checkTime(a);


    document.getElementById('clock').innerHTML =
        `<h1>${weekdays[d]}, ${a} ${monthnames[o]}, ${y}, <span id="clocktime">${h}:${m}:${s}</h1>`;
    var t = setTimeout(startTime, 500);
}

function checkTime(i) {
    if (i < 10) { i = "0" + i };  // Fügt vor einstelligen Zahlen (i > 10) eine Null hinzu
    return i;
}

startTime()

答案 2 :(得分:2)

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