Go Down

Topic: Get IP Address of Anyone Connected to my Arduino set up as server (Read 4 times) previous topic - next topic

joshiek1990

I started off with my Arduino Ethernet shield by making a simple LED flashing light controlled by the web browser. I posted the link on Facebook and the light started to flash a lot! I wanted to see the IP addresses of the people connecting, but I could not for the life of me figure out how to. Help?

If it matters, here is my code (adapted from the example Web Server included in the software)


Code: [Select]
/*
  Web  Server - Modified

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>
#define redLED 2

// Enter a MAC address and IP address for your controller below.
// The IP address will be dependent on your local network:
byte mac[] = { 0xDE, 0xAA, 0xBE, 0xEF, 0xFE, 0xED };
byte ip[] = { 192,168,1, 177 };
byte gateway[] = { 192,168,1, 1 };
byte subnet[] = { 255, 255, 0, 0 };

int foo = 0;
String newLine = "";
// Initialize the Ethernet server library
// with the IP address and port you want to use
// (port 80 is default for HTTP):
Server server(80);
boolean redLEDmode = false;

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

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();
       // Serial.print(c);
       
       if (newLine.length() < 100){
         newLine.concat(c);
       }
        // 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'){
          //test if the string starts with GET
          byte rip[4];
         // Serial.print();
          Serial.print(rip[0]);
          Serial.print(".");
          Serial.print(rip[1]);
          Serial.print(".");
          Serial.print(rip[2]);
          Serial.print(".");
          Serial.print(rip[3]);
          Serial.print("\n");
          //Serial.print("line recieved\n");
          if(newLine.indexOf("GET")!= -1){
            Serial.print("get ");
            //see what "file" was requested
            if(newLine.indexOf("On") !=-1){
              Serial.print("ON\n");
              digitalWrite(redLED,HIGH);
              redLEDmode = true;
            }else if(newLine.indexOf("Off")!= -1){
              Serial.print("OFF\n");
              digitalWrite(redLED,LOW);
              redLEDmode = false;
            }
           
           
          }
         
         
          if(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
           client.print("<html><head><title>Arduino!!</title><script type=\"text/javascript\">");         
           client.print("function toggle(each){");
           // client.print("alert('th');");
           client.print("$.ajax({\ntype:'get',\nasync:true,\nurl:each});\n");
           client.print("$('#current').html(each);}");
           client.print("</script><script type=\"text/javascript\" src=\"http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js\">");
           client.print("</script>");
           client.print("<body>");
           client.print("<div>Red LED is currently<span id=\"current\">");
          if(redLEDmode){
            client.print("ON");
           }else{
            client.print("OFF");
           }
           client.print("</span></div>");
           client.print("<input type=\"button\" onclick=\"toggle('On')\" value=\"Red LED On\" />");         
           client.print("<input type=\"button\" onclick=\"toggle('Off')\" value=\"Red LED Off\" />");
           client.print("<div id=\"test\"></div>");
           client.print("</body>");
           break;
          }
        }
        if (c == '\n') {
          // you're starting a new line
          currentLineIsBlank = true;
          newLine = "";
        }
        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();
  }

}

Jeremy-arduino

This is something that I too am interested in learning how to do. If anyone has any info, that would be much appreciated!  :)

bubulindo

If you are using an Ethernet Shield with a W5100 chip, this seems to be possible to do... however, there isn't any library method programmed yet to do it in the Ethernet library.

If you download the W5100 manual and move down to page 31, you can see that the register Sn_DIPR holds the Destination IP address that can be written when in client mode or read when in server mode.

It's weekend now, so I won't have time for this. But maybe on Monday I can put together a function to test this and share with you guys.

Eu não sou o teu criado. Se respondo no fórum é para ajudar todos mediante a minha disponibilidade e disposição. Responder por mensagem pessoal iria contra o propósito do fórum e por isso evito-o.
Se realmente pretendes que eu te ajude por mensagem pessoal, então podemos chegar a um acordo e contrato onde me pagas pela ajuda que eu fornecer e poderás então definir os termos de confidencialidade do meu serviço. De forma contrária toda e qualquer ajuda que eu der tem de ser visível a todos os participantes do fórum (será boa ideia, veres o significado da palavra fórum).
Nota também que eu não me responsabilizo por parvoíces escritas neste espaço pelo que se vais seguir algo dito por mim, entende que o farás por tua conta e risco.

Dito isto, mensagens pessoais só se forem pessoais, ou seja, se já interagimos de alguma forma no passado ou se me pretendes convidar para uma churrascada com cerveja (paga por ti, obviamente).

bubulindo

#3
Mar 07, 2011, 01:28 pm Last Edit: Mar 07, 2011, 01:35 pm by bubulindo Reason: 1
Hello,

I just put up a method for this.
If you can follow my directions it's easy enough to do it. :)

Find the files:
- Resources\Java\libraries\Ethernet\Client.cpp
- Resources\Java\libraries\Ethernet\Client.h

on the .cpp file add the following code
Code: [Select]

Client::Client(uint8_t *ip, uint16_t port) {
 _ip = ip;
 _port = port;  
 _sock = 255;
}

//what you need to add starts here
void Client::IP_address(uint8_t * addr)
{
getSn_DIPR(_sock, addr);

}


Then on the .h file you should add:
Code: [Select]

void stop();
void IP_address(uint8_t * addr);//Only add this line as the others already exist
uint8_t connected();



Finally, a sketch made by me to test this could be:
Code: [Select]

/*
* Web Server
*
* A simple web server that shows the value of the analog input pins.
*/

#include <Ethernet.h>

byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
byte ip[] = { 192, 168, 1, 67 };
byte client_ip[4];//added

Server server(80);

void setup()
{
 Ethernet.begin(mac, ip);
 server.begin();
}

void loop()
{
 Client client = server.available();
 if (client) {
   // an http request ends with a blank line
   boolean current_line_is_blank = true;
   while (client.connected()) {
     if (client.available()) {
       char c = client.read();
       // if we've gotten to the end of the line (received a newline
       // character) and the line is blank, the http request has ended,
       // so we can send a reply
       if (c == '\n' && current_line_is_blank) {
         // 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 i = 0; i < 6; i++) {
           client.print("analog input ");
           client.print(i);
           client.print(" is ");
           client.print(analogRead(i));
           client.println("<br />");
         }
         
         client.IP_address(&client_ip[0]);//added
         client.println("Your IP is:");//added
         for (int n = 0; n<=3; n++)//added
           {//added
           client.print((int)client_ip[n]);//added
           client.print(".");//added
           }//added
           
         break;
       }
       if (c == '\n') {
         // we're starting a new line
         current_line_is_blank = true;
       } else if (c != '\r') {
         // we've gotten a character on the current line
         current_line_is_blank = false;
       }
     }
   }
   // give the web browser time to receive the data
   delay(1);
   client.stop();
 }
}


I hijacked the example as I'm not good with the Arduino syntax. I've added a tag on the lines I've written myself.
It is also possible to read the port and Mac Address of the device you're connected to, but since you define which port you listen to clients, that isn't so useful.
Eu não sou o teu criado. Se respondo no fórum é para ajudar todos mediante a minha disponibilidade e disposição. Responder por mensagem pessoal iria contra o propósito do fórum e por isso evito-o.
Se realmente pretendes que eu te ajude por mensagem pessoal, então podemos chegar a um acordo e contrato onde me pagas pela ajuda que eu fornecer e poderás então definir os termos de confidencialidade do meu serviço. De forma contrária toda e qualquer ajuda que eu der tem de ser visível a todos os participantes do fórum (será boa ideia, veres o significado da palavra fórum).
Nota também que eu não me responsabilizo por parvoíces escritas neste espaço pelo que se vais seguir algo dito por mim, entende que o farás por tua conta e risco.

Dito isto, mensagens pessoais só se forem pessoais, ou seja, se já interagimos de alguma forma no passado ou se me pretendes convidar para uma churrascada com cerveja (paga por ti, obviamente).

Jeremy-arduino

Thank you for your help and the example, but I just looked through my entire arduino folder and can not find either of those files. Could you give me an idea where I might find them? Thanks.

Jeremy

Go Up