delay(300);
-
-
while (client.available()) {
-
char c = client.read();
-
Serial.print(c);
35
}
-
-
Serial.println("Disconnecting.");
-
client.stop();
-
}
40
}
-
-
void print_ip_address(IPAddress ip) {
-
const unsigned int OCTETS = 4;
-
Serial.print("We've got the following IP address: ");
45
for (unsigned int i = 0; i < OCTETS; i++) {
-
Serial.print(ip[i]);
-
if (i != OCTETS - 1)
-
Serial.print(".");
-
}
50
Serial.println();
-
}
-
This program does the same as the program in the previous section, but it
doesn’t contain any explicit IP addresses. Apart from that, it doesn’t differ
much from the original version. The first difference is in line 8. Here we no
longer declare the variable
time_server
as an
IPAddress
object but as a string. The
string contains the name of the server we’re going to connect to.
In line 13, we no longer pass our own IP address to
Ethernet
’s
begin
method. In
this case,
begin
tries to obtain an unique IP address using a DHCP server in
the local network. If it cannot obtain an IP address, we start an endless loop
that prints an error message every second. Otherwise, we print the IP address
we’ve got, using a small helper function named
print_ip_address
.
Eventually, in line 27, we pass our
time_server
string to the
connect
method. Note
that we didn’t change the line; we’ve only changed the type of the
time_server
variable. If
connect
gets a string and not an
IPAddress
object, it tries to look up
the IP address belonging to the server name stored in the string using DNS.
Run the program, and you’ll see output similar to the following:
We've got the following IP address: 192.168.2.113
Connecting...connected.
56807 14-11-04 16:34:18 50 0 0 259.2 UTC(NIST) *
Disconnecting.
report erratum • discuss
Using DHCP and DNS • 179
www.it-ebooks.info