Web server su un'altra porta

Salve a tutti!

Il mio simpaticissimo modem router non ne vuole sapere di collaborare sulla porta 80.

Dopo svariate prove ho appurato che:

-il programma funziona(nella sub net)

-sulla porta 80 le normali impostazioni non bastano

Se tiro su un banalissimo server (stile easysertver) per es sulla porta 8181 il server risponde dal web.

Quindi, la domanda è semplice:

L'esempio "web server" dell ide, funziona solo con la porta 80? posso inizzializzarlo sul qualcos'altro??

ciao!

Anche io tempo fa avevo fatto una prova e ho riscontrato questo.

Chiamando arduino dall'esterno con ip pubblico xxx.xxx.xxx.xxx:9800 il mio router mi fa un forward su l'IP di arduino ma devo obbligatoriamente passare dal router ad arduino con la porta 80, cambiarla infondo ha poco senso visto che la porta 80 riconosce dati derivanti da protocollo http

ciao

Se ho capito bene, la risposta e qua:

Server server(80);

Basta cambiare il valore 80 con quello desiderato. Io ho provato l' 81 e funziona.
Sul router come detto prima bisogna fare un forwarding (o server virtuale dipende dal router) verso l'ip dell'Arduino specificando la porta corretta.

Per finire sul browser bisogna inserire l'indirizzo pubblico seguito da : ed infine dalla porta configurata

indirizzopubblico:porta

Ciao..

si che poi sarebbe nella IDE 1.0

EthernetServer server(80);

se metti ad esempio

EthernetServer server(1970);

da detro la lan 192.168.2.177:1970 non ci entri .... pagina non trovata
ci entri sempre con 192.168.2.177 senza specificare = default 80

dall'esterno ci entro sempre con ip pubblico xxx.xxx.xxx.xxx:9800 nonostante ci sia 1970 nello sketch

Utilizzando la porta 81 non funziona nemmeno nella mia sub net!!! =( =( =( =(.

Appena provato.

Il codice utilizzato è il seguente:
ripeto: se uso la porta 80 funziona, per la 81 non risponde

/*
  Web  Server
 
 A simple web server that shows the value of the analog input pins.
 using an Arduino Wiznet Ethernet shield. 
 
 Circuit:
 * Ethernet shield attached to pins 10, 11, 12, 13
 * Analog inputs attached to pins A0 through A5 (optional)
 
 created 18 Dec 2009
 by David A. Mellis
 modified 4 Sep 2010
 by Tom Igoe
 
 */

#include <SPI.h>
#include <Ethernet.h>

// Enter a MAC address and IP address for your controller below.
// The IP address will be dependent on your local network:
byte mac[] = { 0x90, 0xA2, 0xDA, 0x00, 0x77, 0x49 };
byte ip[] = { 192,168,0, 4 };

// Initialize the Ethernet server library
// with the IP address and port you want to use 
// (port 80 is default for HTTP):
Server server(80);

void setup()
{
  // start the Ethernet connection and the server:
  Ethernet.begin(mac, ip);
  server.begin();
}

void loop()
{
  // listen for incoming clients
  Client client = server.available();
  if (client) {
    // an http request ends with a blank line
    boolean currentLineIsBlank = true;
    while (client.connected()) {
      if (client.available()) {
        char c = client.read();
        // if you've gotten to the end of the line (received a newline
        // character) and the line is blank, the http request has ended,
        // so you can send a reply
        if (c == '\n' && currentLineIsBlank) {
          // send a standard http response header
          client.println("HTTP/1.1 200 OK");
          client.println("Content-Type: text/html");
          client.println();

          // output the value of each analog input pin
          for (int analogChannel = 0; analogChannel < 6; analogChannel++) {
            client.print("analog input ");
            client.print(analogChannel);
            client.print(" is ");
            client.print(analogRead(analogChannel));
            client.println("
");
          }
          break;
        }
        if (c == '\n') {
          // you're starting a new line
          currentLineIsBlank = true;
        } 
        else if (c != '\r') {
          // you've gotten a character on the current line
          currentLineIsBlank = false;
        }
      }
    }
    // give the web browser time to receive the data
    delay(1);
    // close the connection:
    client.stop();
  }
}

Utilizzando la porta 81 non funziona nemmeno nella mia sub net!!! smiley-cry smiley-cry smiley-cry smiley-cry.

si lui ha fatto l'esempio con ip pubblico non interno alla rete "indirizzopubblico:porta", perchè vuoi cambiarlo?

ciao

Dalla 80 il modem router non fa passare le richieste.
qualunque tentativo è stato vano

Poi ho testato un server sulla 8181 e funziona.

Per cui al posto di star li a sfondarmi con la porta 80 voglio affirare il problema

Ciao Renzo,
e corretto cambiare porta sopratutto se ti interfacci sul lato internet.
Spesso i firewall dei router bloccano la porta 80 proprio per evitare attacchi da mal intenzionati.

Comunque l'esempio della porta 81 a me funziona sia in locale che in web ma di porte ce ne sono tante.
Evita solo di usare quelle che vengono adoperati da servizi conosciuti usa quelle TCP

Non si sa mai che ti servano per altre funzioni

e corretto cambiare porta sopratutto se ti interfacci sul lato internet.
Spesso i firewall dei router bloccano la porta 80 proprio per evitare attacchi da mal intenzionati.

Ma se hai un forward su router con una porta xxxxx che ti importa cambiarla anche localmente? di cosa hai paura di un ATTACCO SOLARE!! http://tubeencore.com/watch/?v=Z1y3yWWR1o0 :smiley:
Comunque a me con 81 e qualsiasi altra porta metto, vengono totalmente ignorate lo raggiungo in locale sempre omettendo la porta quindi per default si prende sempre la 80, se invece scrivo iplocale:porta non va.....
potresti fare un esempio funzionante con una porta diversa chiamato da 192.168.1.1:1970?

ciao

le porte 80, 8080 e 8081 sono particolari, alcuni router le usano per cose loro interne, es. la porta 80 può essere utilizzata per l'accesso remoto al webserver del router per la configurazione.
Così anche per altre well known ports tipo 22, 23 ecc...
Usate porte alte, ricordatevi di nattare l'ip di arduino e la porta usata (sia tcp che udp) sul router in modo che instradi correttamente le richieste provenienti dall'esterno e vedrete che funzionerà tutto :slight_smile:

Metto lo sketch su cui sto studiando, dentro dovete cambiare l'ip e il gateway.
La porta in uso e la 700. A priori dovete vederlo in locale prima di mettere mani sul router.

// ********************        Caricamento delle librerie       ********************
#include <Ethernet.h>
#include <SPI.h>

// ********************        Configurazione della rete        ********************
byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED }; // mac address
byte ip[] = { 192, 168, 10, 25 };                    // Indirizzo IP arduino
byte gateway[] = { 192, 168, 10, 1 };                // Indirizzo GTW arduino
byte subnet[] = { 255, 255, 255, 0 };                // Subnet Mask arduino
EthernetServer server(700);

// ********************        Definizione degli ingressi       ********************
#define LamSalSX       7       // RELE' 1
#define LamSalDX1      8       // RELE' 2
#define LamSalDX2      9       // RELE' 3

// ********************      Configurazione degli ingressi      ********************
boolean STATUSLamSalSX  = false; // Imposta a falso il valore iniziale della stringa STATUSLamSalSX
boolean STATUSLamSalDX1 = false; // Imposta a falso il valore iniziale della stringa STATUSLamSalDX1
boolean STATUSLamSalDX2 = false; // Imposta a falso il valore iniziale della stringa STATUSLamSalDX2
String readString = String(100);

// ********************    Configurazione Sensore temperatura   ********************
float temp;                      // Variabile della temperatura da calcolare
float tempPin = 1;               // Pin analogico di ingresso del sensore della temperatura
float tempreg = 25.0;            // temperatura di controllo in celsius

void setup(){
Ethernet.begin(mac, ip, gateway, subnet); // Attivazione della scheda di rete
pinMode(LamSalSX, OUTPUT);       // Attivazione del PIN LamSalSX come uscita
pinMode(LamSalDX1, OUTPUT);      // Attivazione del PIN LamSalDX1 come uscita
pinMode(LamSalDX2, OUTPUT);      // Attivazione del PIN LamSalDX2 come uscita
Serial.begin(9600);              // Attivazione della porta seriale
}

void loop(){
// ********************   Calcolo e taratura della temperatura  ********************
temp = ((5.0 * analogRead(tempPin) * 100.0 ) / 1023);   // lettura del valore della temperatura moltiplicato 500 e diviso 1023

// ******************** Verifica della connessione di un client ********************
EthernetClient client = server.available();                   // Avvio del Client ethernet
if (client) {
  while (client.connected()) {                        // Controlla se il Client e connesso
  if (client.available()) {                           // Legge il valore Client
    char c = client.read();

      if (readString.length() < 100) {
        readString = readString + c;
        }
      Serial.print(c);
      if (c == '\n') {
        if(readString.indexOf("1=On+%2F+Off") > -1) {
          if(STATUSLamSalSX) { //se ON lo spegne
            digitalWrite(LamSalSX, LOW);    // Spegni la lampada salotto SX
            STATUSLamSalSX=false;          // Imposta lo STATUSLamSalSX a FALSE
          }
          else { //se OFF lo accende
            digitalWrite(LamSalSX, HIGH);   // Accendi la lampada salotto SX
            STATUSLamSalSX = true;          // Imposta lo STATUSLamSalSX a TRUE
          }
        }
        if(readString.indexOf("2=On+%2F+Off") > -1) {
          if(STATUSLamSalDX1) { //se ON lo spegne
            digitalWrite(LamSalDX1, LOW);   // Spegni la lampada salotto DX1
            STATUSLamSalDX1=false;          // Imposta lo STATUSLamSalDX1 a FALSE
          }
          else { //se OFF lo accende
            digitalWrite(LamSalDX1, HIGH);  // Accendi la lampada salotto DX1
            STATUSLamSalDX1 = true;         // Imposta lo STATUSLamSalDX1 a TRUE
          }
        }
        if(readString.indexOf("3=On+%2F+Off") > -1) {
          if(STATUSLamSalDX2) { //se ON lo spegne
            digitalWrite(LamSalDX2, LOW);   // Spegni la lampada salotto DX2
            STATUSLamSalDX2=false;          // Imposta lo STATUSLamSalDX2 a FALSE
          }
          else { //se OFF lo accende
            digitalWrite(LamSalDX2, HIGH);  // Accendi la lampada salotto DX2
            STATUSLamSalDX2 = true;         // Imposta lo STATUSLamSalDX2 a TRUE          }
          }
        }
        if(readString.indexOf("all=Spegni") > -1){
          digitalWrite(LamSalSX, LOW);      // Spegni la lampada salotto SX
          digitalWrite(LamSalDX1, LOW);     // Spegni la lampada salotto DX1
          digitalWrite(LamSalDX2, LOW);     // Spegni la lampada salotto DX2
        }

// ********************       Creazione della pagina HTML       ********************
client.println("HTTP/1.1 200 OK");
client.println("Content-Type: text/html");
client.println();
// ***** HEAD *****
client.print("<html><head>");
client.print("<title>HOMEDuino</title>");
client.println("</head>");
// ***** BODY *****
client.print("<body>");
client.println("<div style='width:360px; height:640px;'>");                    // Risoluzione per cellulari 640x360
client.println("<center><font color='#2076CD'>Gestione HOME ARDUINO</font color></center>");

client.println("<p><font size='6'><span style='color:RED; font-weight:bold;'>SENSORI</span></font></p><hr />"); // Scrivi il titolo e traccia una riga
client.println("<h3>Temperatura = ");                                          // Scrivi la descrizione
client.print(temp);                                                            // Scrivi il valore affianco alla descrizione
client.print(" °C 
</h3>");

client.println("
");
client.println("<table><tr>");

client.println("<td><font face='Verdana' size='2'>LamSalSX</font></td>");
client.println("<td><form method=get><input type=submit name=1 value='On / Off'></form></td>");

client.println("</tr><tr><td><font face='Verdana' size='2'>LamSalDX1</font></td>");
client.println("<td><form method=get><input type=submit name=2 value='On / Off'></form></td>");

client.println("</tr><tr><td><font face='Verdana' size='2'>LamSalDX2</font></td>");
client.println("<td><form method=get><input type=submit name=3 value='On / Off'></form></td>");

client.println("</tr><tr><td><font face='Verdana' size='2'>Spegni tutto</font></td><td><form method=get><input type=submit name=all value='Spegni'></form></td>");

client.println("</tr><table></div></body></html>");
readString="";
client.stop();
}}}}}

Spero vi sia utile...

non vale :smiley: usi ancora la 0022-0023 la ethernet con la 1.0 è molto più affidabile e ha risolto molti problemi

Hai ragione, usavo la 1.0 ma ieri ho provato la 0023... ad ogni modo lo corretto e provato con la 1.0....
Sono nuovo ed ho voluto provare anche l'altra versione per vedere ciò che cambiava :wink:

Ricontrolla pure... ovvio che l'ho provata sulla mia mega 2560 con shield ethernet

Ciao

Ragazzi qui sto rischiando di perdere il pancreas per il nervoso.. :0

Qualunque porta io cambio non lo vede se non sulla 80 c***o.

Ergo sto sbagliando qualcosa.

Se modifico Server server(80) ==> Server server(700), cosa altro devo modificare dello sketc??

Ciao...

la risposta e sempre la stessa,

EthernetServer server(8181);

cosi facendo la tua pagina web la trovi sulla porta 8181

ciao,
da poco sto usando il modulo l'ethernet con lo slot uSD, ho caricato con la 1.0 l'esempio BlinkLed.. tutto bene sulla rete 'interna', come faccio (utilizzando quell'esempio) e far funzionare il tutto dall'esterno?... mi date qualche dritta, non ci salto fuori.... allego l'esempio che sto usando
grazie a tutti

// -- c++ --
//
// Copyright 2010 Ovidiu Predescu ovidiu@gmail.com
// Date: December 2010
// Updated: 08-JAN-2012 for Arduno IDE 1.0 by Hardcore@hardcoreforensics.com
//

#include <pins_arduino.h>
#include <SPI.h>
#include <Ethernet.h>
#include <Flash.h>
#include <SD.h>
#include <TinyWebServer.h>

/***VALUES YOU CHANGE/
// The LED attached to PIN X on an Arduino board.
const int LEDPIN = 7;

// pin 4 is the SPI select pin for the SDcard
const int SD_CS = 4;

// pin 10 is the SPI select pin for the Ethernet
const int ETHER_CS = 10;

// Don't forget to modify the IP to an available one on your home network
byte ip[] = { 192, 168, 0, 18 };

/*********************************************/

static uint8_t mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };

// The initial state of the LED
int ledState = LOW;

void setLedEnabled(boolean state) {
ledState = state;
digitalWrite(LEDPIN, ledState);
}

inline boolean getLedState() { return ledState; }

boolean file_handler(TinyWebServer& web_server);
boolean blink_led_handler(TinyWebServer& web_server);
boolean led_status_handler(TinyWebServer& web_server);
boolean index_handler(TinyWebServer& web_server);

TinyWebServer::PathHandler handlers[] = {
// Work around Arduino's IDE preprocessor bug in handling /* inside
// strings.
//
// `put_handler' is defined in TinyWebServer
{"/", TinyWebServer::GET, &index_handler },
{"/upload/" "", TinyWebServer::PUT, &TinyWebPutHandler::put_handler },
{"/blinkled", TinyWebServer::POST, &blink_led_handler },
{"/ledstatus" "
", TinyWebServer::GET, &led_status_handler },
{"/" "*", TinyWebServer::GET, &file_handler },
{NULL},
};

const char* headers[] = {
"Content-Length",
NULL
};

TinyWebServer web = TinyWebServer(handlers, headers);

boolean has_filesystem = true;
Sd2Card card;
SdVolume volume;
SdFile root;
SdFile file;

void send_file_name(TinyWebServer& web_server, const char* filename) {
if (!filename) {
web_server.send_error_code(404);
web_server << F("Could not parse URL");
} else {
TinyWebServer::MimeType mime_type
= TinyWebServer::get_mime_type_from_filename(filename);
web_server.send_error_code(200);
web_server.send_content_type(mime_type);
web_server.end_headers();
if (file.open(&root, filename, O_READ)) {
Serial << F("Read file "); Serial.println(filename);
web_server.send_file(file);
file.close();
} else {
web_server << F("Could not find file: ") << filename << "\n";
}
}
}

boolean file_handler(TinyWebServer& web_server) {
char* filename = TinyWebServer::get_file_from_path(web_server.get_path());
send_file_name(web_server, filename);
free(filename);
return true;
}

boolean blink_led_handler(TinyWebServer& web_server) {
web_server.send_error_code(200);
web_server.send_content_type("text/plain");
web_server.end_headers();
// Reverse the state of the LED.
setLedEnabled(!getLedState());
Client& client = web_server.get_client();
if (client.available()) {
char ch = (char)client.read();
if (ch == '0') {
setLedEnabled(false);
} else if (ch == '1') {
setLedEnabled(true);
}
}
return true;
}

boolean led_status_handler(TinyWebServer& web_server) {
web_server.send_error_code(200);
web_server.send_content_type("text/plain");
web_server.end_headers();
Client& client = web_server.get_client();
client.println(getLedState(), DEC);
return true;
}

boolean index_handler(TinyWebServer& web_server) {
send_file_name(web_server, "INDEX.HTM");
return true;
}

void file_uploader_handler(TinyWebServer& web_server,
TinyWebPutHandler::PutAction action,
char* buffer, int size) {
static uint32_t start_time;
static uint32_t total_size;

switch (action) {
case TinyWebPutHandler::START:
start_time = millis();
total_size = 0;
if (!file.isOpen()) {
// File is not opened, create it. First obtain the desired name
// from the request path.
char* fname = web_server.get_file_from_path(web_server.get_path());
if (fname) {
Serial << F("Creating ") << fname << "\n";
file.open(&root, fname, O_CREAT | O_WRITE | O_TRUNC);
free(fname);
}
}
break;

case TinyWebPutHandler::WRITE:
if (file.isOpen()) {
file.write(buffer, size);
total_size += size;
}
break;

case TinyWebPutHandler::end:
file.sync();
Serial << F("Wrote ") << file.fileSize() << F(" bytes in ")
<< millis() - start_time << F(" millis (received ")
<< total_size << F(" bytes)\n");
file.close();
}
}

void setup() {
Serial.begin(115200);
Serial << F("Free RAM: ") << FreeRam() << "\n";

pinMode(LEDPIN, OUTPUT);
setLedEnabled(false);

pinMode(SS_PIN, OUTPUT); // set the SS pin as an output
// (necessary to keep the board as
// master and not SPI slave)
digitalWrite(SS_PIN, HIGH); // and ensure SS is high

// Ensure we are in a consistent state after power-up or a reset
// button These pins are standard for the Arduino w5100 Rev 3
// ethernet board They may need to be re-jigged for different boards
pinMode(ETHER_CS, OUTPUT); // Set the CS pin as an output
digitalWrite(ETHER_CS, HIGH); // Turn off the W5100 chip! (wait for
// configuration)
pinMode(SD_CS, OUTPUT); // Set the SDcard CS pin as an output
digitalWrite(SD_CS, HIGH); // Turn off the SD card! (wait for
// configuration)

// initialize the SD card.
Serial << F("Setting up SD card...\n");
// Pass over the speed and Chip select for the SD card
if (!card.init(SPI_FULL_SPEED, SD_CS)) {
Serial << F("card failed\n");
has_filesystem = false;
}
// initialize a FAT volume.
if (!volume.init(&card)) {
Serial << F("vol.init failed!\n");
has_filesystem = false;
}
if (!root.openRoot(&volume)) {
Serial << F("openRoot failed");
has_filesystem = false;
}

if (has_filesystem) {
// Assign our function to `upload_handler_fn'.
TinyWebPutHandler::put_handler_fn = file_uploader_handler;
}

// Initialize the Ethernet.
Serial << F("Setting up the Ethernet card...\n");
Ethernet.begin(mac, ip);

// Start the web server.
Serial << F("Web server starting...\n");
web.begin();

Serial << F("Ready to accept HTTP requests.\n");
}

void loop() {
if (has_filesystem) {
web.process();
}
}

Bhe dovresti dirci come è strutturata la tua rete locale, hai un router tuo, di alice, di susanna :), fastweb ecc

comunque si tratta di

  1. conoscere l'ip pubblico del tuo router
  2. entrare nel setup del router e reindirizzare le richieste da internet con una porta a tua scelta (che sia libera e non usata dal sistema, mail, ftp, ecc) verso l'ip di arduino alla voce "forwarding"

ps : questo pezzo lo puoi anche cancellare non ti serve

void file_uploader_handler(TinyWebServer& web_server,
            TinyWebPutHandler::PutAction action,
            char* buffer, int size) {
  static uint32_t start_time;
  static uint32_t total_size;

  switch (action) {
  case TinyWebPutHandler::START:
    start_time = millis();
    total_size = 0;
    if (!file.isOpen()) {
      // File is not opened, create it. First obtain the desired name
      // from the request path.
      char* fname = web_server.get_file_from_path(web_server.get_path());
      if (fname) {
   Serial << F("Creating ") << fname << "\n";
   file.open(&root, fname, O_CREAT | O_WRITE | O_TRUNC);
   free(fname);
      }
    }
    break;

  case TinyWebPutHandler::WRITE:
    if (file.isOpen()) {
      file.write(buffer, size);
      total_size += size;
    }
    break;

  case TinyWebPutHandler::END:
    file.sync();
    Serial << F("Wrote ") << file.fileSize() << F(" bytes in ")
      << millis() - start_time << F(" millis (received ")
           << total_size << F(" bytes)\n");
    file.close();
  }
}

e anche questa {"/upload/" "*", TinyWebServer::PUT, &TinyWebPutHandler::put_handler },

ciao

// Don't forget to modify the IP to an available one on your home network
byte ip[] = { 192, 168, 0, 18 };
byte gateway[] = { 192, 168, 0, 1 }; // In teoria il gateway e 0,1 finali, ma potrebbe anche essere 0,254 o altro
byte subnet[] = { 255, 255, 255, 0 }; // Subnet ci sta sempre
EthernetServer server(80); // Questa e la porta incriminata, decidila tu...

per il tuo IP PUBBLICO vai sul sito www.ilmioip.it cosi lo scopri.
Per aprire le porte del firewall/router mi serve sapere che router hai.. almeno la marca..

Ciao

.... si scusate ho dato poche informazioni per il problema.... allora il mio router è un netgear ed ho anche assegnato ed 'aperto' una porta per arduino (ho provato diverse numerazioni), come provider uso DYNDNS... una domanda: ma devo modificare qualcosa nel codice, devo indicare nel codice la porta assegnata?
grazie....

Buongiorno a te, ok usi il servizio dyndns quindi ti e semplice raggiungerlo dall'esterno, invece il provider e chi ti da il servizio internet ma poco importa.
Netgear e ottimo per questo un bel prodotto.

nello sketch aggiungi e modifica le scritte che ti messo nel post prima... che ti ho commentato.

Sul netgear ce un forward della porta...