I am currently writing an app where the user needs to know the IP address of their phone/tablet. Where would I find this information?
I only want to know what the local IP address is, such as, 192.168.x.xxx and NOT the public IP address of the router.
So far, I can only seem to find InternetAddress.anyIPv4 and InternetAddress.loopbackIPv4. The loopback address is not what I want as it is 127.0.0.1.
I guess you mean the local IP of the currently connected Wifi network, right?
EDITED
In this answer, I used to suggest using the NetworkInterface in 'dart:io', however NetworkInterface.list is not supported in all Android devices (as pointed out by Mahesh). The wifi package provides that, but later this was incorporated to the flutter's connectivity plugin. In Oct/2020 the methods for that were moved from the connectivity to the wifi_info_flutter plugin, and in 2021 that package was discontinued in favor of network_info_plus.
So just go for network_info_plus and call await NetworkInfo().getWifiIP().
By the way, you may also want to check if Wifi is available using the connectivity_plus plugin in flutter/plugins. Here's an example of how to check if wifi is available.
This provides the IP addresses of all interfaces
import 'dart:io';
...
Future printIps() async {
for (var interface in await NetworkInterface.list()) {
print('== Interface: ${interface.name} ==');
for (var addr in interface.addresses) {
print(
'${addr.address} ${addr.host} ${addr.isLoopback} ${addr.rawAddress} ${addr.type.name}');
}
}
}
See also
https://api.dartlang.org/stable/2.0.0/dart-io/NetworkInterface-class.html
I was searching for getting IP address in flutter for both the iOS and android platforms.
As answered by Feu and Günter Zöchbauer following works on only iOS platform
NetworkInterface.list(....);
this listing of network interfaces is not supported for android platform.
After too long search and struggling with possible solutions, for getting IP also on android device, I came across a flutter package called wifi, with this package we can get device IP address on both iOS and android platforms.
Simple sample function to get device IP address
Future<InternetAddress> get selfIP async {
String ip = await Wifi.ip;
return InternetAddress(ip);
}
I have tested this on android using wifi and also from mobile network.
And also tested on iOS device.
Though from name it looks only for wifi network, but it has also given me correct IP address on mobile data network [tested on 4G network].
#finally_this_works : I have almost given up searching for getting IP address on android and was thinking of implementing platform channel to fetch IP natively from java code for android platform [as interface list was working for iOS]. This wifi package saved the day and lots of headache.
It seems that Dart doesn't have a solution to get your own ip address. Searching for a solution I came across the rest api https://ipify.org to get my public address. Hope it helps.
Here is another way.
Future<InternetAddress> _retrieveIPAddress() async {
InternetAddress result;
int code = Random().nextInt(255);
var dgSocket = await RawDatagramSocket.bind(InternetAddress.anyIPv4, 0);
dgSocket.readEventsEnabled = true;
dgSocket.broadcastEnabled = true;
Future<InternetAddress> ret =
dgSocket.timeout(Duration(milliseconds: 100), onTimeout: (sink) {
sink.close();
}).expand<InternetAddress>((event) {
if (event == RawSocketEvent.read) {
Datagram dg = dgSocket.receive();
if (dg != null && dg.data.length == 1 && dg.data[0] == code) {
dgSocket.close();
return [dg.address];
}
}
return [];
}).firstWhere((InternetAddress a) => a != null);
dgSocket.send([code], InternetAddress("255.255.255.255"), dgSocket.port);
return ret;
}
here, you can use this package https://pub.dev/packages/dart_ipify available on pub.dev,
import 'package:dart_ipify/dart_ipify.dart';
void main() async {
final ipv4 = await Ipify.ipv4();
print(ipv4); // 98.207.254.136
final ipv6 = await Ipify.ipv64();
print(ipv6); // 98.207.254.136 or 2a00:1450:400f:80d::200e
final ipv4json = await Ipify.ipv64(format: Format.JSON);
print(ipv4json); //{"ip":"98.207.254.136"} or {"ip":"2a00:1450:400f:80d::200e"}
// The response type can be text, json or jsonp
}
To get device connected network/WiFi IP you can use network_info_plus package.
For android add the following permissions ACCESS_COARSE_LOCATION and ACCESS_FINE_LOCATION in the AndroidManifest.xml file
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
IOS permissions are a little more complicated so please read what is requested in the library.
Add package to pubspec.yaml
dependencies:
network_info_plus: ^1.0.2
Than you can get the current IP by executing
String? wifiIP = await NetworkInfo().getWifiIP();
In my recent app I have a requirement to get user's Ip address and then I found this packgage useful. https://pub.dev/packages/get_ip
Here is How I use it.
_onLoginButtonPressed() async {
String ipAddress = await GetIp.ipAddress;
print(ipAddress); //192.168.232.2
}
You can use the wifi package for getting the local IP Address (for eg. 192.168.x.x). (as The NetworkInterface.list (from dart:io) is no longer supporting Android from 7.0 and above).
Use the wifi package :
import 'package:wifi/wifi.dart';
You can retrieve the IP Address like this:
Future<String> getIp() async {
String ip = await Wifi.ip;
return ip;
}
You can display it on a Text widget using FutureBuilder:
FutureBuilder<String>(
future: getIp(),
builder: (BuildContext context, AsyncSnapshot<String> snapshot) {
if (snapshot.connectionState == ConnectionState.waiting) {
return Center(child: CircularProgressIndicator());
} else {
if (snapshot.hasError)
return Center(child: Text('Error: ${snapshot.error}'));
else
return Center(child: Text('IP Address is : ${snapshot.data}')); //IP Address
}
},
);
Have you tried the device_info package?
There is an example on querying device information in https://pub.dartlang.org/packages/device_info#-example-tab-
You can use the network_info_plus plugin to get various info about the wifi connection
Eg:
import 'package:network_info_plus/network_info_plus.dart';
final NetworkInfo _networkInfo = NetworkInfo();
wifiIPv4Addr = await _networkInfo.getWifiIP();
For further refernce you can refer to the examples given under the official page
You can use the following package: https://pub.dev/packages/network_info_plus
And here is the page giving more detail about how to use the package https://plus.fluttercommunity.dev/docs/network_info_plus/usage/#using-network-info-plus
Essentially...if you have the package installed, you would use something like
import 'package:network_info_plus/network_info_plus.dart';
final info = NetworkInfo();
var wifiIP = await info.getWifiIP();
This package comes with some additional methods that could prove quite useful ;)
NOTE: This package is not supported on flutter web.
The flutter network_info_plus package provides access to Wifi information such as Wifi IP and name, but the problem is that it doesn't work when the phone HotSpot is on and the phone gets its IP from its own HotSpot.
The code below works for any condition and returns local IP whether it comes from phone HotSpot or another router:
import 'package:flutter/services.dart';
MethodChannel _channel = const MethodChannel('get_ip');
String ip = await _channel.invokeMethod('getIpAdress');
Node that in case you got No implementation found for method error, you should add get_ip package.
I hope it helps.
If we want to find the public facing IP address of a browser we can use dart_ipify The example in the documentation worked perfectly for me.
Import the package:
import 'package:dart_ipify/dart_ipify.dart';
Add this code to _incrementCounter():
final ipv4 = await Ipify.ipv4();
print(ipv4);
i am new to Appium. I want to perform mobile testing on android and i OS app using appium tool on sauce labs.
I want to know what are the pre-requisites, and how to write the scripts(in java) and how exactly the flow goes.
can anybody help me out??
Thanks a lot in advance.. :-)
package com.saucelabs;
import org.junit.After;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TestName;
import org.openqa.selenium.Platform;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.openqa.selenium.remote.RemoteWebDriver;
import java.net.URL;
import static junit.framework.Assert.assertEquals;
/**
* Simple {#link RemoteWebDriver} test that demonstrates how to run your Selenium tests with Sauce OnDemand.
* *
* #author Ross Rowe
*/
public class DemoScript {
private WebDriver driver;
#Before
public void setUp() throws Exception {
DesiredCapabilities caps = DesiredCapabilities.android();
caps.setCapability("browserName", "");
caps.setCapability("platformVersion", "4.4");
caps.setCapability("appiumVersion", "");
caps.setCapability("platformName", "Android");
caps.setCapability("deviceName", "Android Emulator");
caps.setCapability("device-orientation", "portrait");
/* DesiredCapabilities capabillities = DesiredCapabilities.iphone();
capabillities.setCapability("version", "5.0");
capabillities.setCapability("platform", Platform.MAC);*/
this.driver = new RemoteWebDriver(
new URL("http://**********************"),caps);
}
#Test
public void basic() throws Exception {
driver.get("http://www.amazon.com/");
assertEquals("Amazon.com: Online Shopping for Electronics, Apparel, Computers, Books, DVDs & more", driver.getTitle());
}
#After
public void tearDown() throws Exception {
driver.quit();
}
}
i am new to Appium. I want to perform mobile testing on android and i OS app using appium tool on sauce labs.
I want to know what are the pre-requisites, and how to write the scripts(in java) and how exactly the flow goes.
can anybody help me out??
Thanks a lot in advance.. :-)
Are there any changes required in the code?
Is appium server should be started before running the script?
how can I check using Google Dart if a feature (for example MediaSource) is available.
new MediaSource() throws an error. How to programmatically check if this class or feature exists? Any ideas? Is there an in-build feature for this?
I tried try/catch but it looks like the type of the exception differs on the Browser I use.
EDIT #2
youtube.com/html5 does it like this:
var mse = window['MediaSource'] || window['WebKitMediaSource'];
setCompatibility('c-mse', !!mse);
So should I just use jsobject (dart:js package)?
Regards and Thanks,
Robert
I found this:
import 'dart:js';
bool available = context.hasProperty('MediaSource');
Does anyone have a better solution? To me this looks like the cleanest solution.
Regards, Robert
I think TypeError is thrown, so what about catching the exception if MediaSource doesn't exist?
try {
new MediaSource();
// do something if MediaSource is available
} on TypeError catch(e) {
// do something else if MediaSource is not available
}
Dart provides special annotation:
/**
* An annotation used to mark a feature as only being supported by a subset
* of the browsers that Dart supports by default.
*
* If an API is not annotated with [SupportedBrowser] then it is assumed to
* work on all browsers Dart supports.
*/
class SupportedBrowser {
static const String CHROME = "Chrome";
static const String FIREFOX = "Firefox";
static const String IE = "Internet Explorer";
static const String OPERA = "Opera";
static const String SAFARI = "Safari";
/// The name of the browser.
final String browserName;
/// The minimum version of the browser that supports the feature, or null
/// if supported on all versions.
final String minimumVersion;
const SupportedBrowser(this.browserName, [this.minimumVersion]);
}
for example:
#DomName('ApplicationCache')
#SupportedBrowser(SupportedBrowser.CHROME)
#SupportedBrowser(SupportedBrowser.FIREFOX)
#SupportedBrowser(SupportedBrowser.IE, '10')
#SupportedBrowser(SupportedBrowser.OPERA)
#SupportedBrowser(SupportedBrowser.SAFARI)
#Unstable()
class ApplicationCache extends EventTarget {
...
You can detect browser version and get(with mirrors) annotation of a class that represents some web feature. If it has #Experimental and, probably #Unstable then you can't rely on it even with supported browsers. If it has #SupportedBrowser annotation and users browser is in list or it has no #SupportedBrowser at all then you should be ok.
I am trying to execute a map example using Dart. But I am getting an error
The class JsObject does not have a constructor jsify
The dart code that I am using is
library google_maps;
import 'dart:html' show query;
import 'dart:js' show context, JsObject;
void main() {
// The top-level getter context provides a JsObject that represents the global
// object in JavaScript.
final google_maps = context['google']['maps'];
// new JsObject() constructs a new JavaScript object and returns a proxy
// to it.
var center = new JsObject(google_maps['LatLng'], [-34.397, 150.644]);
var mapTypeId = google_maps['MapTypeId']['ROADMAP'];
// new JsObject.jsify() recursively converts a collection of Dart objects
// to a collection of JavaScript objects and returns a proxy to it.
var mapOptions = new JsObject.jsify({
"center": center,
"zoom": 8,
"mapTypeId": mapTypeId
});
// Nodes are passed though, or transferred, not proxied.
new JsObject(google_maps['Map'], [query('#map-canvas'), mapOptions]);
}
The pubspec.yaml is
name: google_maps_api_with_dart_js
description: An app that displays a location using the JavaScript
Google Maps API that is called using the dart:js library.
dependencies:
browser: ">=0.9.0 <0.10.0"
environment:
sdk: ">=0.8.10+6 <2.0.0"
I got this resolved by shifting to new version
Dart Editor version 1.0.0_r30188 (STABLE)
Dart SDK version 1.0.0.3_r30188
Now it's all working fine.
Thank you!
I found this code, which I guess is for the java file, but does that actually display it, or how do I do the XML? And does Blackberry have a nice GUI for the BB UI yet?
import net.rim.device.api.browser.field2.*;
import net.rim.device.api.ui.*;
import net.rim.device.api.ui.container.*;
public class BrowserFieldDemo extends UiApplication
{
public static void main(String[] args)
{
BrowserFieldDemo app = new BrowserFieldDemo();
app.enterEventDispatcher();
}
public BrowserFieldDemo()
{
pushScreen(new BrowserFieldDemoScreen());
}
}
class BrowserFieldDemoScreen extends MainScreen
{
public BrowserFieldDemoScreen()
{
BrowserFieldConfig myBrowserFieldConfig = new BrowserFieldConfig();
myBrowserFieldConfig.setProperty(BrowserFieldConfig.NAVIGATION_MODE,BrowserFieldConfig.NAVIGATION_MODE_POINTER);
BrowserField browserField = new BrowserField(myBrowserFieldConfig);
add(browserField);
browserField.requestContent("http://www.blackberry.com");
}
}
I got the code from this page
My end-game is to have a web-based app using HTML5 since BB is a b*tch to program. I figure the HTML is super easy, and this way I just have to figure out how to show a webpage. Is there any reason I should not attempt this method?
I found this code, which I guess is for the java file...
Yes
but does that actually display it?
Yes. Why not?
...or how do I do the xml?
Don't get it
And does blackberry have a nice GUI for the BB UI yet?
No. I use BB plugin for Eclipse and it is not hard
My end-game is to have a web-based app using HTML5
Good solution but depends on the app you are trying to develop
...since BB is a b*tch to program
Don't think so
I figure the HTML is super easy, and this way I just have to figure
out how to show a webpage. Is there any reason I should not attempt
this method?
It's good if you want to develop for multiple platforms but you are not going to be able to create an app that is as powerfull as a native one
HTML5 webapp is the best solution since not all BBs use the same code