Notice»

Recent Post»

Recent Comment»

Recent Trackback»

Archive»

« 2024/3 »
1 2
3 4 5 6 7 8 9
10 11 12 13 14 15 16
17 18 19 20 21 22 23
24 25 26 27 28 29 30
31

윈도우8 네트워크 정보

프로그래밍/Windows 10 | 2013. 6. 19. 09:11 | Posted by 99%

1. 네트워크 정보

 

윈도우8앱에서 네트워크를 사용할 경우에는 연결된 네트워크 상태를 확인할 필요가 있다. 데이터가 큰 경우나 실시간으로 데이터를 주고 받을 때는 Background Task를 사용하겠지만 사용한다고 해도 실제 앱에서 체크하여 사용자에게 상태를 알려주거나 관련 처리를 해야 할 경우가 있다. 또한 윈도우8앱은 기본적으로 윈도우 스토어에서 배포하게 되는데 윈도우 스토어  뿐만 아니라 사용자에게 서비스되는 거의 모든 스토어에서는 네트워크를 사용하는 앱에서 사용자에게 네트워크 정보 및 상태를 알리게 가이드 하고 있다.

네트워크 관련 정보에는 현재 연결된 네트워크 정보(Wi-Fi, 3G), 사용시간 정보, 네트워크 장비 정보, 사용 요금 등이 있으며 윈도우8에서는 관련 정보를 Windows.NetworkInformation을 통해 제공한다. 연결된 네트워크 정보는ConnectionProfile을 통해 알 수 있다.

 

[예제 1] 네트워크 정보

private void BtnInternetConnection_Click(object sender, RoutedEventArgs e)

{

    string connectionProfileInfo = string.Empty;

    try

    {

        ConnectionProfile InternetConnectionProfile = NetworkInformation.GetInternetConnectionProfile();

 

        if (InternetConnectionProfile == null)

        {

            txtNetProfile.Text = "인터넷에 연결되지 않음.\n";

        }

        else

        {

            txtNetProfile.Text = GetConnectionProfile(InternetConnectionProfile);

        }

    }

    catch (Exception ex)

    {

        txtNetProfile.Text = "예외 발생: " + ex.ToString();

    }

}

 

private void BtnConnections_Click(object sender, RoutedEventArgs e)

{

    string connectionProfileList = string.Empty;

    try

    {

        IReadOnlyList<ConnectionProfile> ConnectionProfiles = NetworkInformation.GetConnectionProfiles();

        foreach (ConnectionProfile connectionProfile in ConnectionProfiles)

        {

            connectionProfileList += GetConnectionProfile(connectionProfile);

            connectionProfileList += "-----------------------------------------------------\n\n";

        }

        txtNetProfile.Text = connectionProfileList;

    }

    catch (Exception ex)

    {

        txtNetProfile.Text = "예외 발생: " + ex.ToString();

    }

}

 

string GetConnectionProfile(ConnectionProfile connectionProfile)

{

    string connectionProfileInfo = string.Empty;

    if (connectionProfile != null)

    {

        connectionProfileInfo = "Profile Name : " + connectionProfile.ProfileName + "\n";

 

        switch (connectionProfile.GetNetworkConnectivityLevel())

        {

            case NetworkConnectivityLevel.None:

                connectionProfileInfo += "Connectivity Level : None\n";

                break;

            case NetworkConnectivityLevel.LocalAccess:

                connectionProfileInfo += "Connectivity Level : Local Access\n";

                break;

            case NetworkConnectivityLevel.ConstrainedInternetAccess:

                connectionProfileInfo += "Connectivity Level : Constrained Internet Access\n";

                break;

            case NetworkConnectivityLevel.InternetAccess:

                connectionProfileInfo += "Connectivity Level : Internet Access\n";

                break;

        }

    }

    return connectionProfileInfo;

}

 

예제 1는 현재 사용중인 대표 네트워크 정보와 모든 네트워크 정보를 가져오는 두개의 버튼이 추가되어 있으며 현재 인터넷을 사용중인 네트워크 정보를 NetworkInformation.GetInternetConnectionProfile를 통해ConnectionProfile로 얻어 왔다.

리턴된 값이 null이면 연결된 네트워크 정보가 없으며 null이 아니면 ConnectionProfileGetConnectionProfile라는 함수를 통해 정보를 출력해주고 있다. 정보에는ProfileName이라는 네트워크 프로필 이름이 있으며 무선 네트워크 이름과 같고 GetNetworkConnectivityLevel를 통해 현재 사용중인 네트워크의 인터넷 엑세스 정보를 알 수 있다. 그 리턴 값은NetworkConnectivityLevel 열거형으로 되어 있으며InternetAccess은 인터넷 엑세스가 가능하고 LocalAccess은 인터넷이 안되는 로컬망이고ConstrainedInternetAccess은 제한적인 인터넷 엑세스를 나타낸다.

 

<그림1> GetInternetConnectionProfile 결과

 

 <그림2> GetConnectionProfiles 결과

 

NetworkInformation.GetInternetConnectionProfile는 현재 사용중인 대표적인 네트워크 정보만을 나타내므로 한 개의 네트워크 정보만을 반환하지만NetworkInformation.GetConnectionProfiles를 이용하면 모든 네트워크 정보를 IReadOnlyList<ConnectionProfile>로 반환해준다. 이전 사용했던 무선 네트워크 정보도 포함되며 다수의 정보가 포함됐을 뿐 각각의 정보는ConnectionProfile을 통해 제공되므로 사용법은 같다.

 

ConnectionProfile에는 네트워크 사용량 및 데이터 요금제 상태 정보도 포함되어 있으며 관련  정보는 아래와 같다.

 

< 1> 네트워크 사용량 및 데이터 요금제 상태 정보

데이터

제공 요소

설명

연결 비용

ConnectionCost

데이터 제한 및 로밍 정보를 포함하여 연결 비용 정보에 대한 자세한 정보

비용 유형

NetworkCostType

현재 사용하는 네트워크의 비용 유형

데이터 요금제 상태 및 사용량

DataPlanStatus,
DataPlanUsage

데이터 요금제에 대한 사용량 정보

데이터 사용량

DataUsage

데이터 사용량 정보

네트워크 어댑터

NetworkAdapter

네트워크 어댑터를 식별

 

연결 비용은 ConnectionProfileGetConnectionCost를 통해 얻을 수 있고 NetworkCostType을 통해 비용 유형을 알 수 있다. 데이터 요금제 상태 및 네트워크 사용량은 GetDataPlanStatusGetLocalUsage를 통해 확인 할 수 있다. 또한 NetworkAdapter로 네트워크 어댑터정보를 얻어 올 수 있다.

 

윈도우8은 태블릿에서 이동통신망도 사용하므로 앱에서 사용된 데이터 사용량을 확인 할 필요가 있다. 예제를 통해 알아보자.

 

[예제 2] 네트워크 사용량

string localDataUsage = string.Empty;

 DateTime CurrTime = DateTime.Now;

 TimeSpan TimeDiff = new TimeSpan(1, 0, 0);

 

 try

 {

     ConnectionProfile InternetConnectionProfile = NetworkInformation.GetInternetConnectionProfile();

 

     if (InternetConnectionProfile == null)

     {

         txtNetProfile.Text = "인터넷에 연결되지 않음.\n";

     }

     else

     {

         DataUsage LocalUsage = InternetConnectionProfile.GetLocalUsage(CurrTime.Subtract(TimeDiff), me);

 

         localDataUsage = "Local Data Usage:\n";

         localDataUsage += " Bytes Sent     : " + LocalUsage.BytesSent + "\n";

         localDataUsage += " Bytes Received : " + LocalUsage.BytesReceived + "\n";

         txtNetProfile.Text = localDataUsage;

     }

 }

 catch (Exception ex)

 {

     txtNetProfile.Text = "예외 발생: " + ex.ToString();

 }

 

현재 사용중인 네트워크 정보인 ConnectionProfileGetLocalUsage를 통해 DataUsage를 얻어왔다. GetLocalUsage로 데이터를 얻어 올 때 1시간전까지의 데이터를 가져왔으며 BytesSentBytesReceived로 네트워크의 사용량을 확인 할 수 있다.

위 예제들을 이용하면 현재 네트워크의 접속 유무 및 접속된 네트워크의 정보를 가져올 수 있지만 실시간으로 정보를 전달 받기 위해서는NetworkInformation.NetworkStatusChanged를 이용해서 이벤트 핸들러를 등록하면 된다.

 

[예제 3] 네트워크 상태 확인

public static bool registeredNetworkStatusNotif = false;

string internetProfileInfo = string.Empty;

NetworkStatusChangedEventHandler networkStatusCallback = null;

private CoreDispatcher _cd = Window.Current.CoreWindow.Dispatcher;

 

private void BtnNetStatus_Click(object sender, RoutedEventArgs e)

{

    try

    {

        networkStatusCallback = new NetworkStatusChangedEventHandler(OnNetworkStatusChange);

        if (!registeredNetworkStatusNotif)

        {

            NetworkInformation.NetworkStatusChanged += networkStatusCallback;

            registeredNetworkStatusNotif = true;

        }

        if (internetProfileInfo == "")

        {

            txtNetProfile.Text = "네트워크 상태 변경 사항 없음.";

        }

        else

        {

            txtNetProfile.Text = internetProfileInfo;

        }

    }

    catch (Exception ex)

    {

        txtNetProfile.Text = "예외 발생: " + ex.ToString();

    }

}

 

async void OnNetworkStatusChange(object sender)

{

    string connectionProfileInfo = string.Empty;

 

    internetProfileInfo = "네트워크 상태가 변경됨.: \n\r";

 

    try

    {          

        ConnectionProfile InternetConnectionProfile = workInformation.GetInternetConnectionProfile();

 

        if (InternetConnectionProfile == null)

        {

            await _cd.RunAsync(CoreDispatcherPriority.Normal, () =>

            {

                txtNetProfile.Text = "인터넷에 연결되지 않음.\n";

            });

        }

        else

        {

            connectionProfileInfo = GetConnectionProfile(InternetConnectionProfile);

            await _cd.RunAsync(CoreDispatcherPriority.Normal, () =>

            {

                txtNetProfile.Text = connectionProfileInfo;

            });

        }

        internetProfileInfo = "";

    }

    catch (Exception ex)

    {

        txtNetProfile.Text = ("예외 발생: " + ex.ToString());

    }

}

 

void UnRegisterForNetworkStatusChangeNotif()

{

    NetworkInformation.NetworkStatusChanged -= networkStatusCallback;

    internetProfileInfo = "";

    registeredNetworkStatusNotif = false;

}

 

NetworkInformation.NetworkStatusChanged에 이벤트 핸들러를 등록하여 변화된 상태를 전달 받으며ConnectionProfile를 이용해 상태값을 확인한다. 네트워크 상태 확인을 완료하고 싶거나 앱 종료시는UnRegisterForNetworkStatusChangeNotif와 같이 등록된 핸들러를 제거해주면 된다.

 

: