How can i check connection status?

Oct 4, 2012 at 9:34 PM
Edited Oct 4, 2012 at 9:36 PM

Hello, i'm looking for an answer, how can I get connection status?

I have some network, and i'm trying to connect with it. I need connection status for example if password was good then connected, if not then something else. Someone know how can i do that? 

 

private void button1_Click(object sender, EventArgs e)
        {
            button3.Visible = true;
            button1.Visible = false;
            changePos();

            string name2;
            WlanClient client = new WlanClient();
            foreach (WlanClient.WlanInterface wlanIface in client.Interfaces)
            {
                Wlan.WlanBssEntry[] wlanBssEntries = wlanIface.GetNetworkBssList();
                foreach (Wlan.WlanBssEntry network in wlanBssEntries)
                {
                    byte[] macAddr = network.dot11Bssid;
                    string tMac = "";
                    for (int i = 0; i < macAddr.Length; i++)
                    {
                        tMac += macAddr[i].ToString("x2").PadLeft(2, '0').ToUpper();
                    }
                    
                    name2 = GetStringForSSID(network.dot11Ssid);
                    foreach (Wlan.WlanProfileInfo profileInfo in wlanIface.GetProfiles())
                    {
                        string name = profileInfo.profileName; // this is typically the network's SSID
                        string xml = wlanIface.GetProfileXml(profileInfo.profileName);
                    }

                    textBox1.AppendText( GetStringForSSID(network.dot11Ssid) + "\r\n");
                    textBox2.AppendText( network.linkQuality + "%" +"\r\n");
                    textBox3.AppendText( tMac + "\r\n");

                    profileNameList.Add(GetStringForSSID(network.dot11Ssid));
                    macList.Add(tMac); 

                    if (name2 == "test") //if network is avalible then i try to connect
                    {
                        string profileName = GetStringForSSID(network.dot11Ssid); ; // this is also the SSID
                        string mac = ConvertToHex(profileName).ToUpper();
                        string key = "has34";
                        string profileXml = string.Format("<?xml version=\"1.0\"?><WLANProfile xmlns=\"http://www.microsoft.com/networking/WLAN/profile/v1\"><name>{0}</name><SSIDConfig><SSID><hex>{1}</hex><name>{0}</name></SSID></SSIDConfig><connectionType>ESS</connectionType><MSM><security><authEncryption><authentication>open</authentication><encryption>WEP</encryption><useOneX>false</useOneX></authEncryption><sharedKey><keyType>networkKey</keyType><protected>false</protected><keyMaterial>{2}</keyMaterial></sharedKey><keyIndex>0</keyIndex></security></MSM></WLANProfile>", profileName, mac, key);
                        wlanIface.SetProfile(Wlan.WlanProfileFlags.AllUser, profileXml, true);
                        wlanIface.Connect(Wlan.WlanConnectionMode.Profile, Wlan.Dot11BssType.Any, profileName); 
                    } // I NEED STATUS, NEED TO KNOW PASSWORD IS CORRECT OR NOT
                }
            }
        }
	static string GetStringForSSID(Wlan.Dot11Ssid ssid)
        {
            return Encoding.ASCII.GetString(ssid.SSID, 0, (int)ssid.SSIDLength);
        }

        public string ConvertToHex(string asciiString)
        {
            string hex = "";
            foreach (char c in asciiString)
            {
                int tmp = c;
                hex += String.Format("{0:x2}", (uint)System.Convert.ToUInt32(tmp.ToString()));
            }
            return hex;
        }


Darek Musielak.

 

Feb 12, 2014 at 6:25 PM
Same with me, need to know if the connection attempt was successful. Does anyone know that???
Oct 23, 2014 at 5:21 PM
Edited Oct 23, 2014 at 7:28 PM
Under the hood, the WlanInterface.Connect method with those arguments makes an asynchronous call to the Windows API to connect using the profile supplied. This means that it spawns a new thread and the main thread that made the call returns immediately and it has no way of knowing when the other thread will get done with its work of trying to connect to the network. For this reason, the WlanInterface class provides an event to hook into, named WlanNotification, which will fire when it receives notifications from the wireless interface.

First, register your event handler with the event, like so:
         foreach (WlanClient.WlanInterface wlanIface in client.Interfaces)
         {
            wlanIface.WlanNotification  += new                           WlanClient.WlanInterface.WlanNotificationEventHandler(this.HandleNotification);
         }
It is probably better to do that in your form constructor, or somewhere that only gets called once. Otherwise every time that you click the button, you are adding one more event handler instance; thus, after the 5th button click, you will get 5 notifications raised for just the one click. Likewise, there is no need to create a new WlanClient every time the button is clicked. I would say that should be a private field and instantiated in the constructor. In any case, the WlanClient needs to be created before the handler can be registered on its WlanInterface objects.

Then, outside of your button1_Click method, create your event handler. It should check against the return code of the Notification data:
  private void HandleNotification(Wlan.WlanNotificationData notifyData)
  {
     switch (notifyData.notificationSource)
     {
        case Wlan.WlanNotificationSource.ACM:
           switch ((Wlan.WlanNotificationCodeAcm)notifyData.notificationCode)
           {
              case Wlan.WlanNotificationCodeAcm.ConnectionAttemptFail:
                 ...
                 ...
                 break;
              case Wlan.WlanNotificationCodeAcm.ConnectionComplete:
                 ...
                 ...
                 break;
           }
           break;
        case Wlan.WlanNotificationSource.MSM:
           switch ((Wlan.WlanNotificationCodeMsm)notifyData.notificationCode)
           {
              case Wlan.WlanNotificationCodeMsm.Connected:
                 ...
                 ...
                 break;
           }
           break;
     }
  }
It is important to note that the ConnectionComplete notification code is the event fired to signal that the entire Connect sequence has finished. It does not indicate either success or failure of the connection. However, at some point in the sequence, either the ACM code ConnectionAttemptFail or the Msm code Connected will fire, never both. Thus, in their case checks you should set some kind of state which keeps track of which code has fired, and when the ConnectionComplete code fires, act according to whether Connect succeeded or failed.

It is also very important to remember that these events are being raised in a separate thread from your main thread. If you wish to do something to one of your GUI controls from inside the event handler, it is necessary to put that code inside an Invoke so that the main thread can do this.
Example:
            case Wlan.WlanNotificationCodeAcm.ConnectionComplete:
                 if (this.IsHandleCreated)
                 {
                    this.Invoke((MethodInvoker)delegate
                    {
                        this.TextBox1.Text = "Connection Attempt Complete"
                    });
                 }
                 break;
There are other codes fired than just the three I listed, for different network events such as authenticating or disconnecting or what have you; the ones I listed in the code above are just the minimum needed to check for whether Connect succeeded or failed. You can find the other codes in Wlan.WlanNotificationCodeAcm and Wlan.WlanNotificationCodeMsm, defined in interop.cs. Depending on your interface you may also need to call WlanInterface.Scan() and wait for Wlan.WlanNotificationCodeAcm.ScanComplete to fire before getting the list of networks.

Hope this helps!
Jun 9, 2016 at 11:03 PM
don't work
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;
using System.ComponentModel;
using System.Data;
using System.Threading.Tasks;
using System.Net;
using System.Net.Security;
using System.Net.Sockets;
using System.Net.NetworkInformation;
using NativeWifi;
using System.IO;
using System.IO.Compression;
using System.Runtime.InteropServices;
using System.Threading;

namespace cmd
{
    class Program
    {
        static void Main(string[] args)
        {
            
            Console.Clear();
            Console.Title = "cmd";
            Console.WriteLine("User : {0}        Host : {1}        Machine : {2}", Environment.UserName, System.Net.Dns.GetHostName(), Environment.MachineName);
            String Hostname = System.Net.Dns.GetHostName();
            IPHostEntry iphostentry = Dns.GetHostByName(Hostname);
            int nIP = 0;
            foreach (IPAddress ipaddress in iphostentry.AddressList)
            {
                Console.WriteLine("IP #" + ++nIP + ": " +
                 ipaddress.ToString());
            }

            Console.WriteLine("--------------------------------------------------------------------------------");
            Console.WriteLine("--------------------------------------------------------------------------------");


            WlanClient client = new WlanClient();
            string a = "0";
            string b = "0";
            string c = "0";
            string d = "0";
            string e = "0";
            string f = "0";
            foreach (WlanClient.WlanInterface wlanIface in client.Interfaces)
            {

                Wlan.WlanAvailableNetwork[] wlanBssEntries = wlanIface.GetAvailableNetworkList(0);

                foreach (Wlan.WlanAvailableNetwork network in wlanBssEntries)
                {

                    a = System.Text.ASCIIEncoding.ASCII.GetString(network.dot11Ssid.SSID).Trim((char)0);


                    b = (network.wlanSignalQuality.ToString() + "%"); // качество связи в процентах
                    c = (network.dot11DefaultAuthAlgorithm.ToString().Trim((char)0)); // тип безопасности
                    d = (network.dot11DefaultCipherAlgorithm.ToString().Trim((char)0)); // тип шифрования
                    e = (network.dot11BssType.ToString().Trim((char)0));
                    f = (network.profileName.ToString().Trim((char)0));

                    Console.WriteLine("{0,-16} {1,12} {2,15} {3,5} {4,15} {5,5}", a, b, c, d, e, f);

                }
            }
            Console.WriteLine(" ");
            Console.WriteLine(" ");
            Console.Write("ProfileName : ");
            String profileName = Console.ReadLine();
            Console.Write("Key : ");
            String key = Console.ReadLine();

            String hex = profileName;
            byte[] hy = Encoding.Unicode.GetBytes(hex);
            String hex2 = BitConverter.ToString(hy);
            hex = hex2.Replace("-", "");
            hex = hex.Replace("00", "");
            Console.WriteLine(hex);
            try
            {
                WlanClient client1 = new WlanClient();

                foreach (WlanClient.WlanInterface wlanIface in client.Interfaces)
                {
                    Wlan.WlanAvailableNetwork[] wlanBssEntries = wlanIface.GetAvailableNetworkList(0);
                    foreach (Wlan.WlanAvailableNetwork network in wlanBssEntries)
                    {
                        //  String profileName = "DIR-620";

                        String strTemplate = "";
                        String authentication = "";

                        switch ((int)network.dot11DefaultAuthAlgorithm)
                        {
                            case 1: // Open
                                break;
                            case 2: // SHARED_KEY
                                break;
                            case 3: // WPA
                                break;
                            case 4: // WPA_PSK
                                break;
                            case 5: // WPA_NONE
                                break;
                            case 6: // RSNA
                                break;
                            case 7: // RSNA_PSK                           
                                strTemplate = Properties.Resources.WPA2PSK;
                                authentication = "WPA2PSK";
                                String encryption = network.dot11DefaultCipherAlgorithm.ToString().Trim((char)0);
                                //      String key = "76543210";
                                String profileXml = String.Format(strTemplate, profileName, authentication, encryption, key, hex);

                                wlanIface.SetProfile(Wlan.WlanProfileFlags.AllUser, profileXml, true);
                                wlanIface.Connect(Wlan.WlanConnectionMode.Profile, Wlan.Dot11BssType.Any, profileName);
                                Console.ReadLine();
                                break;




                            default:
                                break;
                        }
                    }


                }
            }



            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }

            string text = System.IO.File.ReadAllText("pass.txt");
            System.Console.WriteLine("Contents of WriteText.txt = {0}", text);

            Console.ReadLine();






                WlanClient client2 = new WlanClient();
                foreach (WlanClient.WlanInterface wlanIface in client.Interfaces)
                {
                    wlanIface.WlanNotification += new WlanClient.WlanInterface.WlanNotificationEventHandler(this.OnWlanNotification);
                }


            Console.ReadLine();


        }

        private void OnWlanNotification(ref Wlan.WlanNotificationData notifyData, IntPtr context)
        {
            switch (notifyData.notificationSource)
            {
                case Wlan.WlanNotificationSource.ACM:
                    switch ((Wlan.WlanNotificationCodeAcm)notifyData.notificationCode)
                    {
                        case Wlan.WlanNotificationCodeAcm.ConnectionStart:
                            Console.WriteLine("ConnectionStart");
                            break;
                        case Wlan.WlanNotificationCodeAcm.ConnectionComplete:
                            Console.WriteLine("ConnectionComplete");
                            break;
                        case Wlan.WlanNotificationCodeAcm.ConnectionAttemptFail:
                            Console.WriteLine("ConnectionAttemptFail");
                            break;
                        case Wlan.WlanNotificationCodeAcm.Disconnecting:
                            Console.WriteLine("Disconnecting");
                            break;
                        case Wlan.WlanNotificationCodeAcm.Disconnected:
                            Console.WriteLine("Disconnected");
                            break;
                        case Wlan.WlanNotificationCodeAcm.ScanFail:
                            Console.WriteLine("ScanFail");
                            break;
                    }
                    break;
                case Wlan.WlanNotificationSource.MSM:
                    switch ((Wlan.WlanNotificationCodeMsm)notifyData.notificationCode)
                    {
                        case Wlan.WlanNotificationCodeMsm.Associating:
                            break;
                        case Wlan.WlanNotificationCodeMsm.Associated:
                            break;
                        case Wlan.WlanNotificationCodeMsm.Authenticating:
                            break;
                        case Wlan.WlanNotificationCodeMsm.Connected:
                            break;
                        case Wlan.WlanNotificationCodeMsm.RoamingStart:
                            break;
                        case Wlan.WlanNotificationCodeMsm.RoamingEnd:
                            break;
                        case Wlan.WlanNotificationCodeMsm.Disassociating:
                            break;
                        case Wlan.WlanNotificationCodeMsm.Disconnected:
                            break;
                        case Wlan.WlanNotificationCodeMsm.PeerJoin:
                            break;
                        case Wlan.WlanNotificationCodeMsm.PeerLeave:
                            break;
                        case Wlan.WlanNotificationCodeMsm.AdapterRemoval:
                            break;
                    }
                    break;
            }

        }

    }
}       
Error 2 Keyword 'this' is not valid in a static property, static method, or static field initializer D:\Hack\cmd\Hack\Hack\Program.cs 224 109 Hack
don't like "this" in wlanIface.WlanNotification += new WlanClient.WlanInterface.WlanNotificationEventHandler(this.OnWlanNotification);