/******************************************************************************
*                           snif.cpp                          2000-05-28 AgF  *
*                 Demonstrating browser sniffer                               *
******************************************************************************/

#include <cgi_in.h>     // define cgi interface

// The class BrowserSniffer detects the browser type and version number.
// The type is returned in both name and type:
// type    name
// ----------------------
//  0      Unknown
//  1      Netscape
//  2      Explorer
//  3      Opera
//  4      Amaya
// ----------------------
// The version number is returned in version.
class BrowserSniffer {
   public:
   BrowserSniffer();    // constructor
   char * name;         // browser name (brand)
   int type;            // browser type
   float version;       // version number
   char * agent;        // raw HTTP_USER_AGENT string
   private:
   int SearchFor(char * nm); // used by constructor
};

BrowserSniffer::BrowserSniffer() {
// the constructor does all the sniffing and sets name, type and version
   agent = getenv("HTTP_USER_AGENT"); if (!agent) agent = "";
   name = "Unknown"; type = 0; version = 0;
   if (SearchFor("MSIE")) {name = "Explorer"; type = 2; return;}
   if (SearchFor("Opera")) {type = 3; return;}
   if (SearchFor("Amaya")) {type = 4; return;}
   if (SearchFor("Lynx")) {type = 0; return;}
   if (SearchFor("Mozilla")) {
      if (SearchFor("compatible")) {
         name = "Unknown"; type = 0;}
      else {
         name = "Netscape"; type = 1;}}}

int BrowserSniffer::SearchFor(char * nm) {
// search for the name nm and set name and versíon
   int len = strlen(nm);
   for (char * p = agent; *p; p++) { // search through string
      if (strncasecmp(p, nm, len) == 0) {
         // name found. search for version number
         name = nm;
         for (p++; *p; p++) {
            if (*p >= '0' && *p <= '9') {
               // number found
               version = atof(p);
               return 1;}}
         return 1;}}
   // not found
   return 0;}


void main () {
   // create object
   BrowserSniffer browser;
   // output HTML code
   cout << "<html><head><title>Browser sniffing</title>\n";
   cout << "</head>\n<body>\n";
   cout << "<h1>Browser sniffing</h1>\n";
   cout << "Browser type is " << browser.name << "<br>\n";
   cout << "Version number is " << browser.version << ".\n";
   cout << "</body></html>";}


