2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

【C#・Xamarin.Forms】NetworkInterface.GetIsNetworkAvailable()の落とし穴

Last updated at Posted at 2019-06-01

よくあるサンプル

「インターネットに接続しているか」の検証方法として、NetworkInterface.GetIsNetworkAvailable()メソッドを使った以下のようなソースをよく見かけます。

using System.Net.NetworkInformation;

if(NetworkInterface.GetIsNetworkAvailable())
    Console.WriteLine("接続済");
else
    Console.WriteLine("未接続");

LANケーブルが刺さった状態や、WiFiモジュール等を積んでいる端末でこれを実際に走らせると、有効な接続がなくても利用可能判定となり結果は「接続済」となります。
脳死してコーディングしていたため、半日くらいこれに気づかずハマりました。
これでは「インターネットに接続しているか」の確認はできません。

以下の記事に、対策方法があります。

Windowsストアアプリでインターネット接続されているかどうかを確認する
https://blog.ch3cooh.jp/entry/20140116/1389856295

え、Xamarinじゃ使えないやんけ

わかります。そんなときはXamarin.Essentialsです。
Windows.Networking.Connectivityと同等の機能を提供しています。

Xamarin.Essentials:接続
https://docs.microsoft.com/ja-jp/xamarin/essentials/connectivity

2
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?