title: C++ code to find BSSID OF associated network
body: <blockquote>
    <p><strong>Possible Duplicate:</strong><br>
    <a href="https://stackoverflow.com/questions/5937757/want-to-know-the-essid-of-wireless-network-via-c-in-ubuntu">Want to know the ESSID of wireless network via C++ in UBUNTU</a>  </p>
  </blockquote>
  
  
  
  <p>Hello  I have written the following code which is a part of a project. It is used to find the ESSID of the current associated network. But it has a flaw that it also the displays the ESSID of the network with which I am not associated i.e. if I try to associate myself with a wireless n/w and if it is unsuccessfull i.e. NO DHCP OFFERS ARE RECEIVED, then also it will display the that ESSID with which I have made my attempt.</p>
  
  <p>Is it possible to find the BSSID of current associated wireless network as it is the only way with which I can mark b/w associated and non associated, e.g. with an ioctl call?</p>
  
  <pre><code>int main (void)
  {
      int errno;
      struct iwreq wreq;
  
      CStdString result = "None";
  
      int sockfd;
      char * id;
      char ESSID[20];
      memset(&amp;wreq, 0, sizeof(struct iwreq));
  
      if((sockfd = socket(AF_INET, SOCK_DGRAM, 0)) == -1) {
          fprintf(stderr, "Cannot open socket \n");
          fprintf(stderr, "errno = %d \n", errno);
          fprintf(stderr, "Error description is : %s\n",strerror(errno));
          return result ;
      }
      CLog::Log(LOGINFO,"Socket opened successfully");
  
      FILE* fp = fopen("/proc/net/dev", "r");
      if (!fp)
      {
          // TBD: Error
          return result;
      }
  
      char* line = NULL;
      size_t linel = 0;
      int n;
      char* p;
      int linenum = 0;
      while (getdelim(&amp;line, &amp;linel, '\n', fp) &gt; 0)
      {
          // skip first two lines
          if (linenum++ &lt; 2)
              continue;
  
          p = line;
          while (isspace(*p))
              ++p;
  
          n = strcspn(p, ": \t");
          p[n] = 0;
  
          strcpy(wreq.ifr_name, p);
  
          id = new char[IW_ESSID_MAX_SIZE+100];
          wreq.u.essid.pointer = id;
          wreq.u.essid.length = 100;
          if ( ioctl(sockfd,SIOCGIWESSID, &amp;wreq) == -1 ) {
              continue;
          }
          else
          {
              strcpy(ESSID,id);
              return ESSID;
          }
          free(id);
      }
  
      free(line);
      fclose(fp);
      return result;
  }
  </code></pre>