11
#include "EthernetClient.h"
12
#include "EthernetServer.h"
15
uint16_t EthernetClient::_srcport = 1024;
17
EthernetClient::EthernetClient() : _sock(MAX_SOCK_NUM) {
20
EthernetClient::EthernetClient(uint8_t sock) : _sock(sock) {
23
int EthernetClient::connect(const char* host, uint16_t port) {
24
// Look up the host first
27
IPAddress remote_addr;
29
dns.begin(Ethernet.dnsServerIP());
30
ret = dns.getHostByName(host, remote_addr);
32
return connect(remote_addr, port);
38
int EthernetClient::connect(IPAddress ip, uint16_t port) {
39
if (_sock != MAX_SOCK_NUM)
42
for (int i = 0; i < MAX_SOCK_NUM; i++) {
43
uint8_t s = W5100.readSnSR(i);
44
if (s == SnSR::CLOSED || s == SnSR::FIN_WAIT) {
50
if (_sock == MAX_SOCK_NUM)
54
if (_srcport == 0) _srcport = 1024;
55
socket(_sock, SnMR::TCP, _srcport, 0);
57
if (!::connect(_sock, rawIPAddress(ip), port)) {
62
while (status() != SnSR::ESTABLISHED) {
64
if (status() == SnSR::CLOSED) {
73
size_t EthernetClient::write(uint8_t b) {
77
size_t EthernetClient::write(const uint8_t *buf, size_t size) {
78
if (_sock == MAX_SOCK_NUM) {
82
if (!send(_sock, buf, size)) {
89
int EthernetClient::available() {
90
if (_sock != MAX_SOCK_NUM)
91
return W5100.getRXReceivedSize(_sock);
95
int EthernetClient::read() {
97
if ( recv(_sock, &b, 1) > 0 )
109
int EthernetClient::read(uint8_t *buf, size_t size) {
110
return recv(_sock, buf, size);
113
int EthernetClient::peek() {
115
// Unlike recv, peek doesn't check to see if there's any data available, so we must
122
void EthernetClient::flush() {
127
void EthernetClient::stop() {
128
if (_sock == MAX_SOCK_NUM)
131
// attempt to close the connection gracefully (send a FIN to other side)
133
unsigned long start = millis();
135
// wait a second for the connection to close
136
while (status() != SnSR::CLOSED && millis() - start < 1000)
139
// if it hasn't closed, close it forcefully
140
if (status() != SnSR::CLOSED)
143
EthernetClass::_server_port[_sock] = 0;
144
_sock = MAX_SOCK_NUM;
147
uint8_t EthernetClient::connected() {
148
if (_sock == MAX_SOCK_NUM) return 0;
150
uint8_t s = status();
151
return !(s == SnSR::LISTEN || s == SnSR::CLOSED || s == SnSR::FIN_WAIT ||
152
(s == SnSR::CLOSE_WAIT && !available()));
155
uint8_t EthernetClient::status() {
156
if (_sock == MAX_SOCK_NUM) return SnSR::CLOSED;
157
return W5100.readSnSR(_sock);
160
// the next function allows us to use the client returned by
161
// EthernetServer::available() as the condition in an if-statement.
163
EthernetClient::operator bool() {
164
return _sock != MAX_SOCK_NUM;