Skip to content

Commit a310cb8

Browse files
committed
Proposed fix for issue 243, adding DNS to the Ethernet library. Uses a slightly modified version of the agreed API as the host/port parameters have been moved from the Client constructor to the Client::connect methods. This means it's possible for errors to be returned if the DNS lookup fails and also reduces the RAM footprint of the Client class as it no longer needs to store the host/port for later use in Client::connect.
1 parent a42dc0b commit a310cb8

File tree

9 files changed

+503
-26
lines changed

9 files changed

+503
-26
lines changed

libraries/Ethernet/Client.cpp

+19-3
Original file line numberDiff line numberDiff line change
@@ -10,16 +10,32 @@ extern "C" {
1010
#include "Ethernet.h"
1111
#include "Client.h"
1212
#include "Server.h"
13+
#include "Dns.h"
1314

1415
uint16_t Client::_srcport = 1024;
1516

17+
Client::Client() : _sock(MAX_SOCK_NUM) {
18+
}
19+
1620
Client::Client(uint8_t sock) : _sock(sock) {
1721
}
1822

19-
Client::Client(IPAddress& ip, uint16_t port) : _ip(ip), _port(port), _sock(MAX_SOCK_NUM) {
23+
int Client::connect(const char* host, uint16_t port) {
24+
// Look up the host first
25+
int ret = 0;
26+
DNSClient dns;
27+
IPAddress remote_addr;
28+
29+
dns.begin(Ethernet.dnsServerIP());
30+
ret = dns.getHostByName(host, remote_addr);
31+
if (ret == 1) {
32+
return connect(remote_addr, port);
33+
} else {
34+
return ret;
35+
}
2036
}
2137

22-
uint8_t Client::connect() {
38+
int Client::connect(IPAddress ip, uint16_t port) {
2339
if (_sock != MAX_SOCK_NUM)
2440
return 0;
2541

@@ -38,7 +54,7 @@ uint8_t Client::connect() {
3854
if (_srcport == 0) _srcport = 1024;
3955
socket(_sock, SnMR::TCP, _srcport, 0);
4056

41-
if (!::connect(_sock, _ip.raw_address(), _port)) {
57+
if (!::connect(_sock, ip.raw_address(), port)) {
4258
_sock = MAX_SOCK_NUM;
4359
return 0;
4460
}

libraries/Ethernet/Client.h

+2-4
Original file line numberDiff line numberDiff line change
@@ -8,10 +8,10 @@ class Client : public Stream {
88
public:
99
Client();
1010
Client(uint8_t sock);
11-
Client(IPAddress& ip, uint16_t port);
1211

1312
uint8_t status();
14-
uint8_t connect();
13+
int connect(IPAddress ip, uint16_t port);
14+
int connect(const char *host, uint16_t port);
1515
virtual void write(uint8_t);
1616
virtual void write(const char *str);
1717
virtual void write(const uint8_t *buf, size_t size);
@@ -31,8 +31,6 @@ class Client : public Stream {
3131
private:
3232
static uint16_t _srcport;
3333
uint8_t _sock;
34-
IPAddress _ip;
35-
uint16_t _port;
3634
};
3735

3836
#endif

0 commit comments

Comments
 (0)