diff --git a/.codespellrc b/.codespellrc new file mode 100644 index 00000000..a231f49a --- /dev/null +++ b/.codespellrc @@ -0,0 +1,7 @@ +# See: https://github.com/codespell-project/codespell#using-a-config-file +[codespell] +# In the event of a false positive, add the problematic word, in all lowercase, to a comma-separated list here: +ignore-words-list = nd, +check-filenames = +check-hidden = +skip = ./.git diff --git a/.github/dependabot.yml b/.github/dependabot.yml new file mode 100644 index 00000000..03600dd7 --- /dev/null +++ b/.github/dependabot.yml @@ -0,0 +1,10 @@ +# See: https://docs.github.com/en/github/administering-a-repository/configuration-options-for-dependency-updates#about-the-dependabotyml-file +version: 2 + +updates: + # Configure check for outdated GitHub Actions actions in workflows. + # See: https://docs.github.com/en/github/administering-a-repository/keeping-your-actions-up-to-date-with-dependabot + - package-ecosystem: github-actions + directory: / # Check the repository's workflows under /.github/workflows/ + schedule: + interval: daily diff --git a/.github/workflows/check-arduino.yml b/.github/workflows/check-arduino.yml new file mode 100644 index 00000000..adb330f8 --- /dev/null +++ b/.github/workflows/check-arduino.yml @@ -0,0 +1,28 @@ +name: Check Arduino + +# See: https://docs.github.com/en/free-pro-team@latest/actions/reference/events-that-trigger-workflows +on: + push: + pull_request: + schedule: + # Run every Tuesday at 8 AM UTC to catch breakage caused by new rules added to Arduino Lint. + - cron: "0 8 * * TUE" + workflow_dispatch: + repository_dispatch: + +jobs: + lint: + runs-on: ubuntu-latest + + steps: + - name: Checkout repository + uses: actions/checkout@v4 + + - name: Arduino Lint + uses: arduino/arduino-lint-action@v1 + with: + compliance: specification + library-manager: update + # Always use this setting for official repositories. Remove for 3rd party projects. + official: true + project-type: library diff --git a/.github/workflows/compile-examples.yml b/.github/workflows/compile-examples.yml new file mode 100644 index 00000000..2812cf08 --- /dev/null +++ b/.github/workflows/compile-examples.yml @@ -0,0 +1,128 @@ +name: Compile Examples + +# See: https://docs.github.com/en/free-pro-team@latest/actions/reference/events-that-trigger-workflows +on: + push: + paths: + - ".github/workflows/compile-examples.yml" + - "examples/**" + - "src/**" + pull_request: + paths: + - ".github/workflows/compile-examples.yml" + - "examples/**" + - "src/**" + schedule: + # Run every Tuesday at 8 AM UTC to catch breakage caused by changes to external resources (libraries, platforms). + - cron: "0 8 * * TUE" + workflow_dispatch: + repository_dispatch: + +jobs: + build: + name: ${{ matrix.board.fqbn }} + runs-on: ubuntu-latest + + env: + SKETCHES_REPORTS_PATH: sketches-reports + + strategy: + fail-fast: false + + matrix: + board: + - fqbn: arduino:avr:nano + platforms: | + - name: arduino:avr + artifact-name-suffix: arduino-avr-nano + - fqbn: arduino:avr:mega + platforms: | + - name: arduino:avr + artifact-name-suffix: arduino-avr-mega + - fqbn: arduino:avr:leonardo + platforms: | + - name: arduino:avr + artifact-name-suffix: arduino-avr-leonardo + - fqbn: arduino:megaavr:uno2018 + platforms: | + - name: arduino:megaavr + artifact-name-suffix: arduino-megaavr-uno2018 + - fqbn: arduino:megaavr:nona4809 + platforms: | + - name: arduino:megaavr + artifact-name-suffix: arduino-megaavr-nona4809 + - fqbn: arduino:sam:arduino_due_x_dbg + platforms: | + - name: arduino:sam + artifact-name-suffix: arduino-sam-arduino_due_x_dbg + - fqbn: arduino:samd:arduino_zero_edbg + platforms: | + - name: arduino:samd + artifact-name-suffix: arduino-samd-arduino_zero_edbg + - fqbn: arduino:samd:mkr1000 + platforms: | + - name: arduino:samd + artifact-name-suffix: arduino-samd-mkr1000 + - fqbn: arduino:samd:mkrzero + platforms: | + - name: arduino:samd + artifact-name-suffix: arduino-samd-mkrzero + - fqbn: arduino:samd:mkrwifi1010 + platforms: | + - name: arduino:samd + artifact-name-suffix: arduino-samd-mkrwifi100 + - fqbn: arduino:samd:mkrfox1200 + platforms: | + - name: arduino:samd + artifact-name-suffix: arduino-samd-mkr1200 + - fqbn: arduino:samd:mkrwan1300 + platforms: | + - name: arduino:samd + artifact-name-suffix: arduino-samd-mkrwan1300 + - fqbn: arduino:samd:mkrwan1310 + platforms: | + - name: arduino:samd + artifact-name-suffix: arduino-samd-mkrwan1310 + - fqbn: arduino:samd:mkrgsm1400 + platforms: | + - name: arduino:samd + artifact-name-suffix: arduino-samd-mkrgsm1400 + - fqbn: arduino:samd:mkrnb1500 + platforms: | + - name: arduino:samd + artifact-name-suffix: arduino-samd-mkrnb1500 + - fqbn: arduino:samd:mkrvidor4000 + platforms: | + - name: arduino:samd + artifact-name-suffix: arduino-samd-mkrvidor4000 + - fqbn: arduino:samd:nano_33_iot + platforms: | + - name: arduino:samd + artifact-name-suffix: arduino-samd-nano_33_iot + + steps: + - name: Checkout repository + uses: actions/checkout@v4 + + - name: Compile examples + uses: arduino/compile-sketches@v1 + with: + github-token: ${{ secrets.GITHUB_TOKEN }} + fqbn: ${{ matrix.board.fqbn }} + platforms: ${{ matrix.board.platforms }} + libraries: | + # Install the library from the local path. + - source-path: ./ + # Additional library dependencies can be listed here. + # See: https://github.com/arduino/compile-sketches#libraries + sketch-paths: | + - examples + enable-deltas-report: true + sketches-report-path: ${{ env.SKETCHES_REPORTS_PATH }} + + - name: Save sketches report as workflow artifact + uses: actions/upload-artifact@v4 + with: + if-no-files-found: error + path: ${{ env.SKETCHES_REPORTS_PATH }} + name: sketches-report-${{ matrix.board.artifact-name-suffix }} diff --git a/.github/workflows/report-size-deltas.yml b/.github/workflows/report-size-deltas.yml new file mode 100644 index 00000000..39e2a0ad --- /dev/null +++ b/.github/workflows/report-size-deltas.yml @@ -0,0 +1,24 @@ +name: Report Size Deltas + +# See: https://docs.github.com/en/free-pro-team@latest/actions/reference/events-that-trigger-workflows +on: + push: + paths: + - ".github/workflows/report-size-deltas.yml" + schedule: + # Run at the minimum interval allowed by GitHub Actions. + # Note: GitHub Actions periodically has outages which result in workflow failures. + # In this event, the workflows will start passing again once the service recovers. + - cron: "*/5 * * * *" + workflow_dispatch: + repository_dispatch: + +jobs: + report: + runs-on: ubuntu-latest + steps: + - name: Comment size deltas reports to PRs + uses: arduino/report-size-deltas@v1 + with: + # Regex matching the names of the workflow artifacts created by the "Compile Examples" workflow + sketches-reports-source: ^sketches-report-.+ diff --git a/.github/workflows/spell-check.yml b/.github/workflows/spell-check.yml new file mode 100644 index 00000000..ef7d8941 --- /dev/null +++ b/.github/workflows/spell-check.yml @@ -0,0 +1,22 @@ +name: Spell Check + +# See: https://docs.github.com/en/free-pro-team@latest/actions/reference/events-that-trigger-workflows +on: + push: + pull_request: + schedule: + # Run every Tuesday at 8 AM UTC to catch new misspelling detections resulting from dictionary updates. + - cron: "0 8 * * TUE" + workflow_dispatch: + repository_dispatch: + +jobs: + spellcheck: + runs-on: ubuntu-latest + + steps: + - name: Checkout repository + uses: actions/checkout@v4 + + - name: Spell check + uses: codespell-project/actions-codespell@master diff --git a/.github/workflows/sync-labels.yml b/.github/workflows/sync-labels.yml new file mode 100644 index 00000000..47ac50a4 --- /dev/null +++ b/.github/workflows/sync-labels.yml @@ -0,0 +1,138 @@ +# Source: https://github.com/arduino/tooling-project-assets/blob/main/workflow-templates/sync-labels.md +name: Sync Labels + +# See: https://docs.github.com/en/actions/reference/events-that-trigger-workflows +on: + push: + paths: + - ".github/workflows/sync-labels.ya?ml" + - ".github/label-configuration-files/*.ya?ml" + pull_request: + paths: + - ".github/workflows/sync-labels.ya?ml" + - ".github/label-configuration-files/*.ya?ml" + schedule: + # Run daily at 8 AM UTC to sync with changes to shared label configurations. + - cron: "0 8 * * *" + workflow_dispatch: + repository_dispatch: + +env: + CONFIGURATIONS_FOLDER: .github/label-configuration-files + CONFIGURATIONS_ARTIFACT: label-configuration-files + +jobs: + check: + runs-on: ubuntu-latest + + steps: + - name: Checkout repository + uses: actions/checkout@v4 + + - name: Download JSON schema for labels configuration file + id: download-schema + uses: carlosperate/download-file-action@v2 + with: + file-url: https://raw.githubusercontent.com/arduino/tooling-project-assets/main/workflow-templates/assets/sync-labels/arduino-tooling-gh-label-configuration-schema.json + location: ${{ runner.temp }}/label-configuration-schema + + - name: Install JSON schema validator + run: | + sudo npm install \ + --global \ + ajv-cli \ + ajv-formats + + - name: Validate local labels configuration + run: | + # See: https://github.com/ajv-validator/ajv-cli#readme + ajv validate \ + --all-errors \ + -c ajv-formats \ + -s "${{ steps.download-schema.outputs.file-path }}" \ + -d "${{ env.CONFIGURATIONS_FOLDER }}/*.{yml,yaml}" + + download: + needs: check + runs-on: ubuntu-latest + + strategy: + matrix: + filename: + # Filenames of the shared configurations to apply to the repository in addition to the local configuration. + # https://github.com/arduino/tooling-project-assets/blob/main/workflow-templates/assets/sync-labels + - universal.yml + + steps: + - name: Download + uses: carlosperate/download-file-action@v2 + with: + file-url: https://raw.githubusercontent.com/arduino/tooling-project-assets/main/workflow-templates/assets/sync-labels/${{ matrix.filename }} + + - name: Pass configuration files to next job via workflow artifact + uses: actions/upload-artifact@v4 + with: + path: | + *.yaml + *.yml + if-no-files-found: error + name: ${{ env.CONFIGURATIONS_ARTIFACT }} + + sync: + needs: download + runs-on: ubuntu-latest + + steps: + - name: Set environment variables + run: | + # See: https://docs.github.com/en/actions/reference/workflow-commands-for-github-actions#setting-an-environment-variable + echo "MERGED_CONFIGURATION_PATH=${{ runner.temp }}/labels.yml" >> "$GITHUB_ENV" + + - name: Determine whether to dry run + id: dry-run + if: > + github.event_name == 'pull_request' || + ( + ( + github.event_name == 'push' || + github.event_name == 'workflow_dispatch' + ) && + github.ref != format('refs/heads/{0}', github.event.repository.default_branch) + ) + run: | + # Use of this flag in the github-label-sync command will cause it to only check the validity of the + # configuration. + echo "::set-output name=flag::--dry-run" + + - name: Checkout repository + uses: actions/checkout@v4 + + - name: Download configuration files artifact + uses: actions/download-artifact@v4 + with: + name: ${{ env.CONFIGURATIONS_ARTIFACT }} + path: ${{ env.CONFIGURATIONS_FOLDER }} + + - name: Remove unneeded artifact + uses: geekyeggo/delete-artifact@v4 + with: + name: ${{ env.CONFIGURATIONS_ARTIFACT }} + + - name: Merge label configuration files + run: | + # Merge all configuration files + shopt -s extglob + cat "${{ env.CONFIGURATIONS_FOLDER }}"/*.@(yml|yaml) > "${{ env.MERGED_CONFIGURATION_PATH }}" + + - name: Install github-label-sync + run: sudo npm install --global github-label-sync + + - name: Sync labels + env: + GITHUB_ACCESS_TOKEN: ${{ secrets.GITHUB_TOKEN }} + run: | + # See: https://github.com/Financial-Times/github-label-sync + github-label-sync \ + --labels "${{ env.MERGED_CONFIGURATION_PATH }}" \ + ${{ steps.dry-run.outputs.flag }} \ + ${{ github.repository }} diff --git a/AUTHORS b/AUTHORS index 14097dff..1faeec41 100644 --- a/AUTHORS +++ b/AUTHORS @@ -1,9 +1,8 @@ - Alberto Panu https://github.com/bigjohnson Alasdair Allan https://github.com/aallan Alice Pintus https://github.com/00alis Adrian McEwen https://github.com/amcewen -Arduino LLC http://arduino.cc/ +Arduino LLC https://arduino.cc/ Arnie97 https://github.com/Arnie97 Arturo Guadalupi https://github.com/agdl Bjoern Hartmann https://people.eecs.berkeley.edu/~bjoern/ @@ -33,6 +32,5 @@ Richard Sim Scott Fitzgerald https://github.com/shfitz Thibaut Viard https://github.com/aethaniel Tom Igoe https://github.com/tigoe -WizNet http://www.wiznet.co.kr +WIZnet http://www.wiznet.co.kr Zach Eveland https://github.com/zeveland - diff --git a/README.adoc b/README.adoc index 4dfea8da..ed937b1b 100644 --- a/README.adoc +++ b/README.adoc @@ -1,9 +1,16 @@ -= Ethernet Library for Arduino = +:repository-owner: arduino-libraries +:repository-name: Ethernet + += {repository-name} Library for Arduino = + +image:https://github.com/{repository-owner}/{repository-name}/actions/workflows/check-arduino.yml/badge.svg["Check Arduino status", link="https://github.com/{repository-owner}/{repository-name}/actions/workflows/check-arduino.yml"] +image:https://github.com/{repository-owner}/{repository-name}/actions/workflows/compile-examples.yml/badge.svg["Compile Examples status", link="https://github.com/{repository-owner}/{repository-name}/actions/workflows/compile-examples.yml"] +image:https://github.com/{repository-owner}/{repository-name}/actions/workflows/spell-check.yml/badge.svg["Spell Check status", link="https://github.com/{repository-owner}/{repository-name}/actions/workflows/spell-check.yml"] With the Arduino Ethernet Shield, this library allows an Arduino board to connect to the internet. For more information about this library please visit us at -https://www.arduino.cc/en/Reference/Ethernet +https://www.arduino.cc/en/Reference/{repository-name} == License == diff --git a/docs/api.md b/docs/api.md new file mode 100644 index 00000000..76265c82 --- /dev/null +++ b/docs/api.md @@ -0,0 +1,2607 @@ +# Ethernet Library + +## Ethernet Class + +### `Ethernet.begin()` + +#### Description + +Initializes the Ethernet library and network settings. + +With version 1.0, the library supports DHCP. Using Ethernet.begin(mac) with the proper network setup, the Ethernet shield will automatically obtain an IP address. This increases the sketch size significantly. To make sure the DHCP lease is properly renewed when needed, be sure to call Ethernet.maintain() regularly. + + +#### Syntax + +``` +Ethernet.begin(mac); +Ethernet.begin(mac, ip); +Ethernet.begin(mac, ip, dns); +Ethernet.begin(mac, ip, dns, gateway); +Ethernet.begin(mac, ip, dns, gateway, subnet); +``` + +#### Parameters +- mac: the MAC (Media access control) address for the device (array of 6 bytes). this is the Ethernet hardware address of your shield. Newer Arduino Ethernet Shields include a sticker with the device's MAC address. For older shields, choose your own. +- ip: the IP address of the device (array of 4 bytes) +- dns: the IP address of the DNS server (array of 4 bytes). optional: defaults to the device IP address with the last octet set to 1 +- gateway: the IP address of the network gateway (array of 4 bytes). optional: defaults to the device IP address with the last octet set to 1 +- subnet: the subnet mask of the network (array of 4 bytes). optional: defaults to 255.255.255.0 + +#### Returns +- The DHCP version of this function, Ethernet.begin(mac), returns an int: 1 on a successful DHCP connection, 0 on failure. +- The other versions don't return anything. + +#### Example + +``` +#include +#include + +// the media access control (ethernet hardware) address for the shield: +byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED }; +//the IP address for the shield: +byte ip[] = { 10, 0, 0, 177 }; + +void setup() +{ + Ethernet.begin(mac, ip); +} + +void loop () {} +``` + +### `Ethernet.dnsServerIP()` + +#### Description + +Returns the DNS server IP address for the device. + + +#### Syntax + +``` +Ethernet.dnsServerIP() + +``` + +#### Parameters +none + +#### Returns +- the DNS server IP address for the device (IPAddress). + +#### Example + +``` +#include +#include + +byte mac[] = {0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED}; +IPAddress ip(10, 0, 0, 177); + +void setup() { + Serial.begin(9600); + while (!Serial) { + ; // wait for serial port to connect. Needed for native USB port only + } + + Ethernet.begin(mac, ip); + + Serial.print("The DNS server IP address is: "); + Serial.println(Ethernet.dnsServerIP()); +} + +void loop () {} +``` + +### `Ethernet.gatewayIP()` + +#### Description + +Returns the gateway IP address for the device. + + +#### Syntax + +``` +Ethernet.gatewayIP() + +``` + +#### Parameters +none + +#### Returns +- the gateway IP address for the device (IPAddress). + +#### Example + +``` +#include +#include + +byte mac[] = {0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED}; +IPAddress ip(10, 0, 0, 177); + +void setup() { + Serial.begin(9600); + while (!Serial) { + ; // wait for serial port to connect. Needed for native USB port only + } + + Ethernet.begin(mac, ip); + + Serial.print("The gateway IP address is: "); + Serial.println(Ethernet.gatewayIP()); +} + +void loop () {} +``` + +### `Ethernet.hardwareStatus()` + +#### Description + +Ethernet.hardwareStatus() tells you which WIZnet Ethernet controller chip was detected during Ethernet.begin(), if any. This can be used for troubleshooting. If no Ethernet controller was detected then there is likely a hardware problem. + + +#### Syntax + +``` +Ethernet.hardwareStatus() + +``` + +#### Parameters +none + +#### Returns +- which WIZnet Ethernet controller chip was detected during Ethernet.begin() (EthernetHardwareStatus): + +``` +EthernetNoHardware +EthernetW5100 +EthernetW5200 +EthernetW5500 +``` + +#### Example + +``` +#include +#include + +byte mac[] = {0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED}; +IPAddress ip(10, 0, 0, 177); + +void setup() { + // Open serial communications and wait for port to open: + Serial.begin(9600); + while (!Serial) { + ; // wait for serial port to connect. Needed for native USB port only + } + + Ethernet.begin(mac, ip); + + if (Ethernet.hardwareStatus() == EthernetNoHardware) { + Serial.println("Ethernet shield was not found."); + } + else if (Ethernet.hardwareStatus() == EthernetW5100) { + Serial.println("W5100 Ethernet controller detected."); + } + else if (Ethernet.hardwareStatus() == EthernetW5200) { + Serial.println("W5200 Ethernet controller detected."); + } + else if (Ethernet.hardwareStatus() == EthernetW5500) { + Serial.println("W5500 Ethernet controller detected."); + } +} + +void loop () {} +``` + +### `Ethernet.init()` + +#### Description + +Used to configure the CS (chip select) pin for the Ethernet controller chip. The Ethernet library has a default CS pin, which is usually correct, but with some non-standard Ethernet hardware you might need to use a different CS pin. + + +#### Syntax + +``` +Ethernet.init(sspin) + +``` + +#### Parameters +- sspin: the pin number to use for CS (byte) + +#### Returns +Nothing + +#### Example + +``` +#include +#include + +byte mac[] = {0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED}; +IPAddress ip(10, 0, 0, 177); + +void setup() { + Ethernet.init(53); // use pin 53 for Ethernet CS + Ethernet.begin(mac, ip); +} + +void loop () {} +``` + +### `Ethernet.linkStatus()` + +#### Description + +Tells you whether the link is active. LinkOFF could indicate the Ethernet cable is unplugged or defective. This feature is only available when using the W5200 and W5500 Ethernet controller chips. + + +#### Syntax + +``` +Ethernet.linkStatus() + +``` + +#### Parameters +none + +#### Returns +- the link status (EthernetLinkStatus): + +- Unknown + +- LinkON + +- LinkOFF + +#### Example + +``` +#include +#include + +void setup() { + // Open serial communications and wait for port to open: + Serial.begin(9600); + while (!Serial) { + ; // wait for serial port to connect. Needed for native USB port only + } +} + +void loop () { + if (Ethernet.linkStatus() == Unknown) { + Serial.println("Link status unknown. Link status detection is only available with W5200 and W5500."); + } + else if (Ethernet.linkStatus() == LinkON) { + Serial.println("Link status: On"); + } + else if (Ethernet.linkStatus() == LinkOFF) { + Serial.println("Link status: Off"); + } +} +``` + +### `Ethernet.localIP()` + +#### Description + +Obtains the IP address of the Ethernet shield. Useful when the address is auto assigned through DHCP. + + +#### Syntax + +``` +Ethernet.localIP(); + +``` + +#### Parameters +none + +#### Returns +- the IP address + +#### Example + +``` +#include +#include + +// Enter a MAC address for your controller below. +// Newer Ethernet shields have a MAC address printed on a sticker on the shield +byte mac[] = { + 0x00, 0xAA, 0xBB, 0xCC, 0xDE, 0x02 }; + +// Initialize the Ethernet client library +// with the IP address and port of the server +// that you want to connect to (port 80 is default for HTTP): +EthernetClient client; + +void setup() { + // start the serial library: + Serial.begin(9600); + // start the Ethernet connection: + if (Ethernet.begin(mac) == 0) { + Serial.println("Failed to configure Ethernet using DHCP"); + // no point in carrying on, so do nothing forevermore: + for(;;) + ; + } + // print your local IP address: + Serial.println(Ethernet.localIP()); + +} + +void loop() { + +} +``` + +### `Ethernet.MACAddress()` + +#### Description + +Fills the supplied buffer with the MAC address of the device. + + +#### Syntax + +``` +Ethernet.MACAddress(mac_address) + +``` + +#### Parameters +- mac_address: buffer to receive the MAC address (array of 6 bytes) + +#### Returns +Nothing + +#### Example + +``` +#include +#include + +byte mac[] = {0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED}; +IPAddress ip(10, 0, 0, 177); + +void setup() { + Serial.begin(9600); + while (!Serial) { + ; // wait for serial port to connect. Needed for native USB port only + } + + Ethernet.begin(mac, ip); + + byte macBuffer[6]; // create a buffer to hold the MAC address + Ethernet.MACAddress(macBuffer); // fill the buffer + Serial.print("The MAC address is: "); + for (byte octet = 0; octet < 6; octet++) { + Serial.print(macBuffer[octet], HEX); + if (octet < 5) { + Serial.print('-'); + } + } +} + +void loop () {} + +``` + +### `Ethernet.maintain()` + +#### Description + +Allows for the renewal of DHCP leases. When assigned an IP address via DHCP, ethernet devices are given a lease on the address for an amount of time. With Ethernet.maintain(), it is possible to request a renewal from the DHCP server. Depending on the server's configuration, you may receive the same address, a new one, or none at all. + +You can call this function as often as you want, it will only re-request a DHCP lease when needed (returning 0 in all other cases). The easiest way is to just call it on every loop() invocation, but less often is also fine. Not calling this function (or calling it significantly less then once per second) will prevent the lease to be renewed when the DHCP protocol requires this, continuing to use the expired lease instead (which will not directly break connectivity, but if the DHCP server leases the same address to someone else, things will likely break). + +Ethernet.maintain() was added to Arduino 1.0.1. + + +#### Syntax + +``` +Ethernet.maintain(); + +``` + +#### Parameters +none + +#### Returns + +byte: + +- 0: nothing happened + +- 1: renew failed + +- 2: renew success + +- 3: rebind fail + +- 4: rebind success + +### `Ethernet.setDnsServerIP()` + +#### Description + +Set the IP address of the DNS server. Not for use with DHCP. + + +#### Syntax + +``` +Ethernet.setDnsServerIP(dns_server) + +``` + +#### Parameters +- dns_server: the IP address of the DNS server (IPAddress) + +#### Returns +Nothing + +#### Example + +``` +#include +#include + +byte mac[] = {0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED}; +IPAddress ip(10, 0, 0, 177); +IPAddress myDns(192, 168, 1, 1); + +void setup() { + Ethernet.begin(mac, ip, myDns); + IPAddress newDns(192, 168, 1, 1); + Ethernet.setDnsServerIP(newDns); // change the DNS server IP address +} + +void loop () {} +``` + +### `Ethernet.setGatewayIP()` + +#### Description + +Set the IP address of the network gateway. Not for use with DHCP. + + +#### Syntax + +``` +Ethernet.setGatewayIP(gateway) + +``` + +#### Parameters +- gateway: the IP address of the network gateway (IPAddress) + +#### Returns +Nothing + +#### Example + +``` +#include +#include + +byte mac[] = {0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED}; +IPAddress ip(10, 0, 0, 177); +IPAddress myDns(192, 168, 1, 1); +IPAddress gateway(192, 168, 1, 1); + +void setup() { + Ethernet.begin(mac, ip, myDns, gateway); + IPAddress newGateway(192, 168, 100, 1); + Ethernet.setGatewayIP(newGateway); // change the gateway IP address +} + +void loop () {} +``` + +### `Ethernet.setLocalIP()` + +#### Description + +Set the IP address of the device. Not for use with DHCP. + + +#### Syntax + +``` +Ethernet.setLocalIP(local_ip) + +``` + +#### Parameters +- local_ip: the IP address to use (IPAddress) + +#### Returns +Nothing + +#### Example + +``` +#include +#include + +byte mac[] = {0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED}; +IPAddress ip(10, 0, 0, 177); + +void setup() { + Ethernet.begin(mac, ip); + IPAddress newIp(10, 0, 0, 178); + Ethernet.setLocalIP(newIp); // change the IP address +} + +void loop () {} +``` + +### `Ethernet.setMACAddress()` + +#### Description + +Set the MAC address. Not for use with DHCP. + + +#### Syntax + +``` +Ethernet.setMACAddress(mac) + +``` + +#### Parameters +- mac: the MAC address to use (array of 6 bytes) + +#### Returns +Nothing + +#### Example + +``` +#include +#include + +byte mac[] = {0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED}; +IPAddress ip(10, 0, 0, 177); + +void setup() { + Ethernet.begin(mac, ip); + byte newMac[] = {0x00, 0xAA, 0xBB, 0xCC, 0xDE, 0x02}; + Ethernet.setMACAddress(newMac); // change the MAC address +} + +void loop () {} +``` + +### `Ethernet.setRetransmissionCount()` + +#### Description + +Set the number of transmission attempts the Ethernet controller will make before giving up. The initial value is 8. 8 transmission attempts times the 200 ms default timeout equals a blocking delay of 1600 ms during a communications failure. You might prefer to set a lower number to make your program more responsive in the event something goes wrong with communications. Despite the name, this sets the total number of transmission attempts (not the number of retries after the first attempt fails) so the minimum value you would ever want to set is 1. + + +#### Syntax + +``` +Ethernet.setRetransmissionCount(number) + +``` + +#### Parameters +- number: number of transmission attempts the Ethernet controller should make before giving up (byte) + +#### Returns +Nothing + +#### Example + +``` +#include +#include + +byte mac[] = {0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED}; +IPAddress ip(10, 0, 0, 177); + +void setup() { + Ethernet.begin(mac, ip); + Ethernet.setRetransmissionCount(1); // configure the Ethernet controller to only attempt one transmission before giving up +} + +void loop () {} +``` + +### `Ethernet.setRetransmissionTimeout()` + +#### Description + +Set the Ethernet controller's timeout. The initial value is 200 ms. A 200 ms timeout times the default of 8 attempts equals a blocking delay of 1600 ms during a communications failure. You might prefer to set a shorter timeout to make your program more responsive in the event something goes wrong with communications. You will need to do some experimentation to determine an appropriate value for your specific application. + + +#### Syntax + +``` +Ethernet.setRetransmissionTimeout(milliseconds) + +``` + +#### Parameters +- milliseconds: the timeout duration (uint16_t) + +#### Returns +Nothing + +#### Example + +``` +#include +#include + +byte mac[] = {0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED}; +IPAddress ip(10, 0, 0, 177); + +void setup() { + Ethernet.begin(mac, ip); + Ethernet.setRetransmissionTimeout(50); // set the Ethernet controller's timeout to 50 ms +} + +void loop () {} +``` + +### `Ethernet.setSubnetMask()` + +#### Description + +Set the subnet mask of the network. Not for use with DHCP. + + +#### Syntax + +``` +Ethernet.setSubnetMask(subnet) + +``` + +#### Parameters +- subnet: the subnet mask of the network (IPAddress) + +#### Returns +Nothing + +#### Example + +``` +#include +#include + +byte mac[] = {0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED}; +IPAddress ip(10, 0, 0, 177); +IPAddress myDns(192, 168, 1, 1); +IPAddress gateway(192, 168, 1, 1); +IPAddress subnet(255, 255, 0, 0); + +void setup() { + Ethernet.begin(mac, ip, myDns, gateway, subnet); + IPAddress newSubnet(255, 255, 255, 0); + Ethernet.setSubnetMask(newSubnet); // change the subnet mask +} + +void loop () {} +``` + +### `Ethernet.subnetMask()` + +#### Description + +Returns the subnet mask of the device. + + +#### Syntax + +``` +Ethernet.subnetMask() + +``` + +#### Parameters +none + +#### Returns +- the subnet mask of the device (IPAddress) + +#### Example + +``` +#include +#include + +byte mac[] = {0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED}; +IPAddress ip(10, 0, 0, 177); + +void setup() { + Serial.begin(9600); + while (!Serial) { + ; // wait for serial port to connect. Needed for native USB port only + } + + Ethernet.begin(mac, ip); + + Serial.print("The subnet mask is: "); + Serial.println(Ethernet.subnetMask()); +} + +void loop () {} +``` + +## IPAddress Class + +### `IPAddress()` + +#### Description + +Defines an IP address. It can be used to declare both local and remote addresses. + + +#### Syntax + +``` +IPAddress(address); + +``` + +#### Parameters +- address: a comma delimited list representing the address (4 bytes, ex. 192, 168, 1, 1) + +#### Returns +None + +#### Example + +``` +#include +#include + +// network configuration. dns server, gateway and subnet are optional. + + // the media access control (ethernet hardware) address for the shield: +byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED }; + +// the dns server ip +IPAddress dnServer(192, 168, 0, 1); +// the router's gateway address: +IPAddress gateway(192, 168, 0, 1); +// the subnet: +IPAddress subnet(255, 255, 255, 0); + +//the IP address is dependent on your network +IPAddress ip(192, 168, 0, 2); + +void setup() { + Serial.begin(9600); + + // initialize the ethernet device + Ethernet.begin(mac, ip, dnServer, gateway, subnet); + //print out the IP address + Serial.print("IP = "); + Serial.println(Ethernet.localIP()); +} + +void loop() { +} +``` + +## Server Class + +### `Server` + +#### Description +Server is the base class for all Ethernet server based calls. It is not called directly, but invoked whenever you use a function that relies on it. + +### `EthernetServer()` + +#### Description + +Create a server that listens for incoming connections on the specified port. + + +#### Syntax + +``` +Server(port); + +``` + +#### Parameters +- port: the port to listen on (int) + +#### Returns +None + +#### Example + +``` +#include +#include + +// network configuration. gateway and subnet are optional. + + // the media access control (ethernet hardware) address for the shield: +byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED }; +//the IP address for the shield: +byte ip[] = { 10, 0, 0, 177 }; +// the router's gateway address: +byte gateway[] = { 10, 0, 0, 1 }; +// the subnet: +byte subnet[] = { 255, 255, 0, 0 }; + +// telnet defaults to port 23 +EthernetServer server = EthernetServer(23); + +void setup() +{ + // initialize the ethernet device + Ethernet.begin(mac, ip, gateway, subnet); + + // start listening for clients + server.begin(); +} + +void loop() +{ + // if an incoming client connects, there will be bytes available to read: + EthernetClient client = server.available(); + if (client == true) { + // read bytes from the incoming client and write them back + // to any clients connected to the server: + server.write(client.read()); + } +} +``` + +### `server.begin()` + +#### Description + +Tells the server to begin listening for incoming connections. + + +#### Syntax + +``` +server.begin() + +``` + +#### Parameters +None + +#### Returns +None + +#### Example + +``` +#include +#include + +// the media access control (ethernet hardware) address for the shield: +byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED }; +//the IP address for the shield: +byte ip[] = { 10, 0, 0, 177 }; +// the router's gateway address: +byte gateway[] = { 10, 0, 0, 1 }; +// the subnet: +byte subnet[] = { 255, 255, 0, 0 }; + +// telnet defaults to port 23 +EthernetServer server = EthernetServer(23); + +void setup() +{ + // initialize the ethernet device + Ethernet.begin(mac, ip, gateway, subnet); + + // start listening for clients + server.begin(); +} + +void loop() +{ + // if an incoming client connects, there will be bytes available to read: + EthernetClient client = server.available(); + if (client == true) { + // read bytes from the incoming client and write them back + // to any clients connected to the server: + server.write(client.read()); + } +} +``` + +### `server.accept()` + +#### Description + +The traditional server.available() function would only tell you of a new client after it sent data, which makes some protocols like FTP impossible to properly implement. + +The intention is programs will use either available() or accept(), but not both. With available(), the client connection continues to be managed by EthernetServer. You don’t need to keep a client object, since calling available() will give you whatever client has sent data. Simple servers can be written with very little code using available(). + +With accept(), EthernetServer gives you the client only once, regardless of whether it has sent any data. You must keep track of the connected clients. This requires more code, but you gain more control. + + +#### Syntax + +``` +server.accept() + +``` + +#### Parameters +none + +#### Returns +- a Client object. If no client has data available for reading, this object will evaluate to false in an if-statement. (EthernetClient). + +#### Example + +``` +#include +#include + +byte mac[] = {0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED}; +IPAddress ip(192, 168, 69, 104); + +// telnet defaults to port 23 +EthernetServer server(23); + +EthernetClient clients[8]; + +void setup() { + Ethernet.begin(mac, ip); + + // Open serial communications and wait for port to open: + Serial.begin(9600); + while (!Serial) { + ; // wait for serial port to connect. Needed for native USB port only + } + + // start listening for clients + server.begin(); +} + +void loop() { + // check for any new client connecting, and say hello (before any incoming data) + EthernetClient newClient = server.accept(); + if (newClient) { + for (byte i = 0; i < 8; i++) { + if (!clients[i]) { + newClient.print("Hello, client number: "); + newClient.println(i); + // Once we "accept", the client is no longer tracked by EthernetServer + // so we must store it into our list of clients + clients[i] = newClient; + break; + } + } + } + + // check for incoming data from all clients + for (byte i = 0; i < 8; i++) { + while (clients[i] && clients[i].available() > 0) { + // read incoming data from the client + Serial.write(clients[i].read()); + } + } + + // stop any clients which disconnect + for (byte i = 0; i < 8; i++) { + if (clients[i] && !clients[i].connected()) { + clients[i].stop(); + } + } +} +``` + +### `server.available()` + +#### Description + +Gets a client that is connected to the server and has data available for reading. The connection persists when the returned client object goes out of scope; you can close it by calling client.stop(). + + +#### Syntax + +``` +server.available() + +``` + +#### Parameters +None + +#### Returns +- a Client object; if no Client has data available for reading, this object will evaluate to false in an if-statement (see the example below) + +#### Example + +``` +#include +#include + +// the media access control (ethernet hardware) address for the shield: +byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED }; +//the IP address for the shield: +byte ip[] = { 10, 0, 0, 177 }; +// the router's gateway address: +byte gateway[] = { 10, 0, 0, 1 }; +// the subnet: +byte subnet[] = { 255, 255, 0, 0 }; + + +// telnet defaults to port 23 +EthernetServer server = EthernetServer(23); + +void setup() +{ + // initialize the ethernet device + Ethernet.begin(mac, ip, gateway, subnet); + + // start listening for clients + server.begin(); +} + +void loop() +{ + // if an incoming client connects, there will be bytes available to read: + EthernetClient client = server.available(); + if (client) { + // read bytes from the incoming client and write them back + // to any clients connected to the server: + server.write(client.read()); + } +} +``` + +### `if(server)` + +#### Description +Indicates whether the server is listening for new clients. You can use this to detect whether server.begin() was successful. It can also tell you when no more sockets are available to listen for more clients, because the maximum number have connected. + + +#### Syntax + +``` +if(server) + +``` + +#### Parameters +none + +#### Returns +- whether the server is listening for new clients (bool). + +#### Example + +``` +#include +#include + +byte mac[] = {0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED}; +IPAddress ip(10, 0, 0, 177); + +// telnet defaults to port 23 +EthernetServer server = EthernetServer(23); + +void setup() { + // Open serial communications and wait for port to open: + Serial.begin(9600); + while (!Serial) { + ; // wait for serial port to connect. Needed for native USB port only + } + + // initialize the Ethernet device + Ethernet.begin(mac, ip); + + // start listening for clients + server.begin(); +} + +void loop() { + if (server) { + Serial.println("Server is listening"); + } + else { + Serial.println("Server is not listening"); + } +} +``` + +### `server.write()` + +#### Description + +Write data to all the clients connected to a server. This data is sent as a byte or series of bytes. + + +#### Syntax + +``` +server.write(val) +server.write(buf, len) + +``` + +#### Parameters +- val: a value to send as a single byte (byte or char) + +- buf: an array to send as a series of bytes (byte or char) + +- len: the length of the buffer + +#### Returns +- byte +- write() returns the number of bytes written. It is not necessary to read this. + +#### Example + +``` +#include +#include + +// network configuration. gateway and subnet are optional. + + // the media access control (ethernet hardware) address for the shield: +byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED }; +//the IP address for the shield: +byte ip[] = { 10, 0, 0, 177 }; +// the router's gateway address: +byte gateway[] = { 10, 0, 0, 1 }; +// the subnet: +byte subnet[] = { 255, 255, 0, 0 }; + +// telnet defaults to port 23 +EthernetServer server = EthernetServer(23); + +void setup() +{ + // initialize the ethernet device + Ethernet.begin(mac, ip, gateway, subnet); + + // start listening for clients + server.begin(); +} + +void loop() +{ + // if an incoming client connects, there will be bytes available to read: + EthernetClient client = server.available(); + if (client == true) { + // read bytes from the incoming client and write them back + // to any clients connected to the server: + server.write(client.read()); + } +} +``` + +### `server.print()` + +#### Description + +Print data to all the clients connected to a server. Prints numbers as a sequence of digits, each an ASCII character (e.g. the number 123 is sent as the three characters '1', '2', '3'). + + +#### Syntax + +``` +server.print(data) +server.print(data, BASE) + +``` + +#### Parameters +- data: the data to print (char, byte, int, long, or string) + +- BASE (optional): the base in which to print numbers: BIN for binary (base 2), DEC for decimal (base 10), OCT for octal (base 8), HEX for hexadecimal (base 16). + +#### Returns +- byte +- print() will return the number of bytes written, though reading that number is optional + + +### `server.println()` + +#### Description + +Print data, followed by a newline, to all the clients connected to a server. Prints numbers as a sequence of digits, each an ASCII character (e.g. the number 123 is sent as the three characters '1', '2', '3'). + + +#### Syntax + +``` +server.println() +server.println(data) +server.println(data, BASE) + +``` + +#### Parameters +- data (optional): the data to print (char, byte, int, long, or string) + +- BASE (optional): the base in which to print numbers: BIN for binary (base 2), DEC for decimal (base 10), OCT for octal (base 8), HEX for hexadecimal (base 16). + +#### Returns +- byte + +- println() will return the number of bytes written, though reading that number is optional + +## Client Class + +### `Client` + +#### Description +Client is the base class for all Ethernet client based calls. It is not called directly, but invoked whenever you use a function that relies on it. + +### `EthernetClient()` + +#### Description + +Creates a client which can connect to a specified internet IP address and port (defined in the client.connect() function). + + +#### Syntax + +``` +EthernetClient() + +``` + +#### Parameters +None + +#### Example + +``` +#include +#include + + +byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED }; +byte ip[] = { 10, 0, 0, 177 }; +byte server[] = { 64, 233, 187, 99 }; // Google + +EthernetClient client; + +void setup() +{ + Ethernet.begin(mac, ip); + Serial.begin(9600); + + delay(1000); + + Serial.println("connecting..."); + + if (client.connect(server, 80)) { + Serial.println("connected"); + client.println("GET /search?q=arduino HTTP/1.0"); + client.println(); + } else { + Serial.println("connection failed"); + } +} + +void loop() +{ + if (client.available()) { + char c = client.read(); + Serial.print(c); + } + + if (!client.connected()) { + Serial.println(); + Serial.println("disconnecting."); + client.stop(); + for(;;) + ; + } +} +``` + +### `if (EthernetClient)` + +#### Description +Indicates if the specified Ethernet client is ready. + + +#### Syntax + +``` +if (client) + +``` + +#### Parameters +none + +#### Returns +- boolean : returns true if the specified client is available. + +#### Example + +``` +#include +#include + + +byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED }; +byte ip[] = { 10, 0, 0, 177 }; +byte server[] = { 64, 233, 187, 99 }; // Google + +EthernetClient client; + +void setup() +{ + Ethernet.begin(mac, ip); + Serial.begin(9600); + + delay(1000); + + Serial.println("connecting..."); + while(!client){ + ; // wait until there is a client connected to proceed + } + if (client.connect(server, 80)) { + Serial.println("connected"); + client.println("GET /search?q=arduino HTTP/1.0"); + client.println(); + } else { + Serial.println("connection failed"); + } +} + +void loop() +{ + if (client.available()) { + char c = client.read(); + Serial.print(c); + } + + if (!client.connected()) { + Serial.println(); + Serial.println("disconnecting."); + client.stop(); + for(;;) + ; + } +} + +``` + +### `client.connected()` + +#### Description + +Whether or not the client is connected. Note that a client is considered connected if the connection has been closed but there is still unread data. + + +#### Syntax + +``` +client.connected() + +``` + +#### Parameters +none + +#### Returns +- Returns true if the client is connected, false if not. + +#### Example + +``` +#include +#include + +byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED }; +byte ip[] = { 10, 0, 0, 177 }; +byte server[] = { 64, 233, 187, 99 }; // Google + +EthernetClient client; + +void setup() +{ + Ethernet.begin(mac, ip); + Serial.begin(9600); + client.connect(server, 80); + delay(1000); + + Serial.println("connecting..."); + + if (client.connected()) { + Serial.println("connected"); + client.println("GET /search?q=arduino HTTP/1.0"); + client.println(); + } else { + Serial.println("connection failed"); + } +} + +void loop() +{ + if (client.available()) { + char c = client.read(); + Serial.print(c); + } + + if (!client.connected()) { + Serial.println(); + Serial.println("disconnecting."); + client.stop(); + for(;;) + ; + } +} +``` + +### `client.connect()` + +#### Description + +Connects to a specified IP address and port. The return value indicates success or failure. Also supports DNS lookups when using a domain name. + + +#### Syntax + +``` +client.connect() +client.connect(ip, port) +client.connect(URL, port) + +``` + +#### Parameters +- ip: the IP address that the client will connect to (array of 4 bytes) + +- URL: the domain name the client will connect to (string, ex.:"arduino.cc") + +- port: the port that the client will connect to (int) + +#### Returns +- Returns an int (1,-1,-2,-3,-4) indicating connection status : + +- SUCCESS 1 +- TIMED_OUT -1 +- INVALID_SERVER -2 +- TRUNCATED -3 +- INVALID_RESPONSE -4 +#### Example + +``` +#include +#include + +byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED }; +byte ip[] = { 10, 0, 0, 177 }; +byte server[] = { 64, 233, 187, 99 }; // Google + +EthernetClient client; + +void setup() +{ + Ethernet.begin(mac, ip); + Serial.begin(9600); + + delay(1000); + + Serial.println("connecting..."); + + if (client.connect(server, 80)) { + Serial.println("connected"); + client.println("GET /search?q=arduino HTTP/1.0"); + client.println(); + } else { + Serial.println("connection failed"); + } +} + +void loop() +{ + if (client.available()) { + char c = client.read(); + Serial.print(c); + } + + if (!client.connected()) { + Serial.println(); + Serial.println("disconnecting."); + client.stop(); + for(;;) + ; + } +} +``` + +### `client.localPort()` + +#### Description + +Returns the local port number the client is connected to. + + +#### Syntax + +``` +client.localPort + +``` + +#### Parameters +none + +#### Returns +- the local port number the client is connected to (uint16_t). + +#### Example + +``` +#include +#include + +byte mac[] = {0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED}; +IPAddress ip(10, 0, 0, 177); + +// telnet defaults to port 23 +EthernetServer server = EthernetServer(23); + +void setup() { + // Open serial communications and wait for port to open: + Serial.begin(9600); + while (!Serial) { + ; // wait for serial port to connect. Needed for native USB port only + } + + // initialize the Ethernet device + Ethernet.begin(mac, ip); + + // start listening for clients + server.begin(); +} + +void loop() { + // if an incoming client connects, there will be bytes available to read: + EthernetClient client = server.available(); + if (client) { + Serial.print("Client is connected on port: "); + Serial.println(client.localPort()); + client.stop(); + } +} +``` + +### `client.remoteIP()` + +#### Description + +Returns the IP address of the client. + + +#### Syntax + +``` +client.remoteIP() + +``` + +#### Parameters +none + +#### Returns +- the client's IP address (IPAddress). + +#### Example + +``` +#include +#include + +byte mac[] = {0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED}; +IPAddress ip(10, 0, 0, 177); + +// telnet defaults to port 23 +EthernetServer server = EthernetServer(23); + +void setup() { + // Open serial communications and wait for port to open: + Serial.begin(9600); + while (!Serial) { + ; // wait for serial port to connect. Needed for native USB port only + } + + // initialize the Ethernet device + Ethernet.begin(mac, ip); + + // start listening for clients + server.begin(); +} + +void loop() { + // if an incoming client connects, there will be bytes available to read: + EthernetClient client = server.available(); + if (client) { + Serial.print("Remote IP address: "); + Serial.println(client.remoteIP()); + client.stop(); + } +} +``` + +### `client.remotePort()` + +#### Description + +Returns the port of the host that sent the current incoming packet. + + +#### Syntax + +``` +client.remotePort() + +``` + +#### Parameters +none + +#### Returns +- the port of the host that sent the current incoming packet (uint16_t). + +#### Example + +``` +#include +#include + +byte mac[] = {0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED}; +IPAddress ip(10, 0, 0, 177); + +// telnet defaults to port 23 +EthernetServer server = EthernetServer(23); + +void setup() { + // Open serial communications and wait for port to open: + Serial.begin(9600); + while (!Serial) { + ; // wait for serial port to connect. Needed for native USB port only + } + + // initialize the Ethernet device + Ethernet.begin(mac, ip); + + // start listening for clients + server.begin(); +} + +void loop() { + // if an incoming client connects, there will be bytes available to read: + EthernetClient client = server.available(); + if (client) { + Serial.print("Remote port: "); + Serial.println(client.remotePort()); + client.stop(); + } +} +``` + +### `client.setConnectionTimeout()` + +#### Description + +Set the timeout for client.connect() and client.stop(). The initial value is 1000 ms. You might prefer to set a lower timeout value to make your program more responsive in the event something goes wrong. + + +#### Syntax + +``` +client.setConnectionTimeout(milliseconds) + +``` + +#### Parameters +- milliseconds: the timeout duration for client.connect() and client.stop() (uint16_t) + +#### Returns +Nothing + +#### Example + +``` +#include +#include + +byte mac[] = {0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED}; +IPAddress ip(10, 0, 0, 177); + +// telnet defaults to port 23 +EthernetServer server = EthernetServer(23); + +void setup() { + // Open serial communications and wait for port to open: + Serial.begin(9600); + while (!Serial) { + ; // wait for serial port to connect. Needed for native USB port only + } + + // initialize the Ethernet device + Ethernet.begin(mac, ip); + + // start listening for clients + server.begin(); +} + +void loop() { + // if an incoming client connects, there will be bytes available to read: + EthernetClient client = server.available(); + if (client) { + client.setConnectionTimeout(100); // set the timeout duration for client.connect() and client.stop() + } +} +``` + +### `client.write()` + +#### Description + +Write data to the server the client is connected to. This data is sent as a byte or series of bytes. + + +#### Syntax + +``` +client.write(val) +client.write(buf, len) + +``` + +#### Parameters +- val: a value to send as a single byte (byte or char) + +- buf: an array to send as a series of bytes (byte or char) + +- len: the length of the buffer + +#### Returns +byte: +- write() returns the number of bytes written. It is not necessary to read this value. + +### `print()` + +#### Description + +Print data to the server that a client is connected to. Prints numbers as a sequence of digits, each an ASCII character (e.g. the number 123 is sent as the three characters '1', '2', '3'). + + +#### Syntax + +``` +client.print(data) +client.print(data, BASE) + +``` + +#### Parameters +- data: the data to print (char, byte, int, long, or string) + +- BASE (optional): the base in which to print numbers: DEC for decimal (base 10), OCT for octal (base 8), HEX for hexadecimal (base 16). +#### Returns +- byte: returns the number of bytes written, though reading that number is optional + +### `client.println()` + +#### Description + +Print data, followed by a carriage return and newline, to the server a client is connected to. Prints numbers as a sequence of digits, each an ASCII character (e.g. the number 123 is sent as the three characters '1', '2', '3'). + + +#### Syntax + +``` +client.println() +client.println(data) +client.print(data, BASE) + +``` + +#### Parameters +- data (optional): the data to print (char, byte, int, long, or string) + +- BASE (optional): the base in which to print numbers: DEC for decimal (base 10), OCT for octal (base 8), HEX for hexadecimal (base 16). + +#### Returns +- byte: return the number of bytes written, though reading that number is optional + + +### `client.available()` + +#### Description + +Returns the number of bytes available for reading (that is, the amount of data that has been written to the client by the server it is connected to). + +available() inherits from the Stream utility class. + + +#### Syntax + +``` +client.available() + +``` + +#### Parameters +none + +#### Returns +- The number of bytes available. + +#### Example + +``` +#include +#include + +byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED }; +byte ip[] = { 10, 0, 0, 177 }; +byte server[] = { 64, 233, 187, 99 }; // Google + +EthernetClient client; + +void setup() +{ + Ethernet.begin(mac, ip); + Serial.begin(9600); + + delay(1000); + + Serial.println("connecting..."); + + if (client.connect(server, 80)) { + Serial.println("connected"); + client.println("GET /search?q=arduino HTTP/1.0"); + client.println(); + } else { + Serial.println("connection failed"); + } +} + +void loop() +{ + if (client.available()) { + char c = client.read(); + Serial.print(c); + } + + if (!client.connected()) { + Serial.println(); + Serial.println("disconnecting."); + client.stop(); + for(;;) + ; + } +} +``` + +### `client.read()` + +#### Description + +Read the next byte received from the server the client is connected to (after the last call to read()). + +read() inherits from the Stream utility class. + + +#### Syntax + +``` +client.read() + +``` + +#### Parameters +none + +#### Returns +- The next byte (or character), or -1 if none is available. + +### `client.flush()` +Waits until all outgoing characters in buffer have been sent. + +flush() inherits from the Stream utility class. + + +#### Syntax + +``` +client.flush() + +``` + +#### Parameters +none + +#### Returns +none + +### `client.stop()` + +#### Description + +Disconnect from the server. + + +#### Syntax + +``` +client.stop() + +``` + +#### Parameters +none + +#### Returns +none + +## EthernetUDP Class + +### `EthernetUDP.begin()` + +#### Description +Initializes the ethernet UDP library and network settings. + + +#### Syntax + +``` +EthernetUDP.begin(localPort); +``` + +#### Parameters +- localPort: the local port to listen on (int) + +#### Returns +- 1 if successful, 0 if there are no sockets available to use. + +#### Example + +``` + +#include + +#include + +#include + + + +// Enter a MAC address and IP address for your controller below. + +// The IP address will be dependent on your local network: + +byte mac[] = { + + 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED }; + +IPAddress ip(192, 168, 1, 177); + + + +unsigned int localPort = 8888; // local port to listen on + + + +// An EthernetUDP instance to let us send and receive packets over UDP + +EthernetUDP Udp; + + + +void setup() { + + // start the Ethernet and UDP: + + Ethernet.begin(mac,ip); + + Udp.begin(localPort); + + + +} + + + +void loop() { +} + + +``` + +### `EthernetUDP.read()` + +#### Description +Reads UDP data from the specified buffer. If no arguments are given, it will return the next character in the buffer. + +This function can only be successfully called after UDP.parsePacket(). + + +#### Syntax + +``` +EthernetUDP.read(); +EthernetUDP.read(packetBuffer, MaxSize); +``` + +#### Parameters +- packetBuffer: buffer to hold incoming packets (char) +- MaxSize: maximum size of the buffer (int) + +#### Returns +- char : returns the characters in the buffer + +#### Example + +``` +#include +#include +#include + +// Enter a MAC address and IP address for your controller below. +// The IP address will be dependent on your local network: +byte mac[] = { + 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED }; +IPAddress ip(192, 168, 1, 177); + +unsigned int localPort = 8888; // local port to listen on + +// An EthernetUDP instance to let us send and receive packets over UDP +EthernetUDP Udp; + +char packetBuffer[UDP_TX_PACKET_MAX_SIZE]; //buffer to hold incoming packet, + +void setup() { + // start the Ethernet and UDP: + Ethernet.begin(mac,ip); + Udp.begin(localPort); + +} + +void loop() { + + int packetSize = Udp.parsePacket(); + if(packetSize) + { + Serial.print("Received packet of size "); + Serial.println(packetSize); + Serial.print("From "); + IPAddress remote = Udp.remoteIP(); + for (int i =0; i < 4; i++) + { + Serial.print(remote[i], DEC); + if (i < 3) + { + Serial.print("."); + } + } + Serial.print(", port "); + Serial.println(Udp.remotePort()); + + // read the packet into packetBuffer + Udp.read(packetBuffer,UDP_TX_PACKET_MAX_SIZE); + Serial.println("Contents:"); + Serial.println(packetBuffer); +} +} +``` + +### `EthernetUDP.write()` + +#### Description +Writes UDP data to the remote connection. Must be wrapped between beginPacket() and endPacket(). beginPacket() initializes the packet of data, it is not sent until endPacket() is called. + + +#### Syntax + +``` +EthernetUDP.write(message); +EthernetUDP.write(buffer, size); + +``` + +#### Parameters + +- message: the outgoing message (char) + +- buffer: an array to send as a series of bytes (byte or char) + +- size: the length of the buffer + +#### Returns +- byte : returns the number of characters sent. This does not have to be read + +#### Example + +``` + + + +#include + +#include + +#include + + + +// Enter a MAC address and IP address for your controller below. + +// The IP address will be dependent on your local network: + +byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED }; + +IPAddress ip(192, 168, 1, 177); + + + +unsigned int localPort = 8888; // local port to listen on + + + +// An EthernetUDP instance to let us send and receive packets over UDP + +EthernetUDP Udp; + + + +void setup() { + + // start the Ethernet and UDP: + + Ethernet.begin(mac,ip); + + Udp.begin(localPort); + +} + + + +void loop() { + + Udp.beginPacket(Udp.remoteIP(), Udp.remotePort()); + + Udp.write("hello"); + + Udp.endPacket(); + +} + + +``` + +### `EthernetUDP.beginPacket()` + +#### Description +Starts a connection to write UDP data to the remote connection + + +#### Syntax + +``` +EthernetUDP.beginPacket(remoteIP, remotePort); +``` + +#### Parameters +- remoteIP: the IP address of the remote connection (4 bytes) +- remotePort: the port of the remote connection (int) +#### Returns +- Returns an int: 1 if successful, 0 if there was a problem resolving the hostname or port. + +#### Example + +``` +#include +#include +#include + +// Enter a MAC address and IP address for your controller below. +// The IP address will be dependent on your local network: +byte mac[] = { + 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED }; +IPAddress ip(192, 168, 1, 177); + +unsigned int localPort = 8888; // local port to listen on + +// An EthernetUDP instance to let us send and receive packets over UDP +EthernetUDP Udp; + +void setup() { + // start the Ethernet and UDP: + Ethernet.begin(mac,ip); + Udp.begin(localPort); + +} + +void loop() { + + Udp.beginPacket(Udp.remoteIP(), Udp.remotePort()); + Udp.write("hello"); + Udp.endPacket(); + +} +``` + +### `EthernetUDP.endPacket()` + +#### Description +Called after writing UDP data to the remote connection. + + +#### Syntax + +``` +EthernetUDP.endPacket(); +``` + +#### Parameters +None + +#### Returns +- Returns an int: 1 if the packet was sent successfully, 0 if there was an error + +#### Example + +``` +#include +#include +#include + +// Enter a MAC address and IP address for your controller below. +// The IP address will be dependent on your local network: +byte mac[] = { + 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED }; +IPAddress ip(192, 168, 1, 177); + +unsigned int localPort = 8888; // local port to listen on + +// An EthernetUDP instance to let us send and receive packets over UDP +EthernetUDP Udp; + +void setup() { + // start the Ethernet and UDP: + Ethernet.begin(mac,ip); + Udp.begin(localPort); + +} + +void loop() { + + Udp.beginPacket(Udp.remoteIP(), Udp.remotePort()); + Udp.write("hello"); + Udp.endPacket(); + +} +``` + +### `EthernetUDP.parsePacket()` + +#### Description +Checks for the presence of a UDP packet, and reports the size. parsePacket() must be called before reading the buffer with UDP.read(). + + +#### Syntax + +``` +EthernetUDP.parsePacket(); +``` + +#### Parameters +None + +#### Returns +- int: the size of a received UDP packet + +#### Example + +``` + +#include // needed for Arduino versions later than 0018 +#include +#include // UDP library from: bjoern@cs.stanford.edu 12/30/2008 + + +// Enter a MAC address and IP address for your controller below. +// The IP address will be dependent on your local network: +byte mac[] = { + 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED }; +IPAddress ip(192, 168, 1, 177); + +unsigned int localPort = 8888; // local port to listen on + +// An EthernetUDP instance to let us send and receive packets over UDP +EthernetUDP Udp; + +void setup() { + // start the Ethernet and UDP: + Ethernet.begin(mac,ip); + Udp.begin(localPort); + + Serial.begin(9600); +} + +void loop() { + // if there's data available, read a packet + int packetSize = Udp.parsePacket(); + if(packetSize) + { + Serial.print("Received packet of size "); + Serial.println(packetSize); + } + delay(10); +} +``` + +### `EthernetUDP.available()` + +#### Description + +Get the number of bytes (characters) available for reading from the buffer. This is data that's already arrived. + +This function can only be successfully called after UDP.parsePacket(). + +available() inherits from the Stream utility class. + + +#### Syntax + +``` +EthernetUDP.available() + +``` + +#### Parameters +None + +#### Returns +- the number of bytes available to read + +#### Example + +``` +#include +#include +#include + +// Enter a MAC address and IP address for your controller below. +// The IP address will be dependent on your local network: +byte mac[] = { + 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED }; +IPAddress ip(192, 168, 1, 177); + +unsigned int localPort = 8888; // local port to listen on + +// An EthernetUDP instance to let us send and receive packets over UDP +EthernetUDP Udp; + +char packetBuffer[UDP_TX_PACKET_MAX_SIZE]; //buffer to hold incoming packet, + +void setup() { + // start the Ethernet and UDP: + Ethernet.begin(mac,ip); + Udp.begin(localPort); + +} + +void loop() { + + int packetSize = Udp.parsePacket(); + if(Udp.available()) + { + Serial.print("Received packet of size "); + Serial.println(packetSize); + Serial.print("From "); + IPAddress remote = Udp.remoteIP(); + for (int i =0; i < 4; i++) + { + Serial.print(remote[i], DEC); + if (i < 3) + { + Serial.print("."); + } + } + Serial.print(", port "); + Serial.println(Udp.remotePort()); + + // read the packet into packetBuffer + Udp.read(packetBuffer,UDP_TX_PACKET_MAX_SIZE); + Serial.println("Contents:"); + Serial.println(packetBuffer); + } +} +``` + +## UDP class + +### `UDP.stop()` + +#### Description + +Disconnect from the server. Release any resource being used during the UDP session. + + +#### Syntax + +``` +UDP.stop() + +``` + +#### Parameters +none + +#### Returns +none + +### `UDP.remoteIP()` + +#### Description +Gets the IP address of the remote connection. + +This function must be called after UDP.parsePacket(). + + +#### Syntax + +``` +UDP.remoteIP(); +``` + +#### Parameters +None + +#### Returns +- 4 bytes : the IP address of the remote connection + +#### Example + +``` + +#include +#include +#include + +// Enter a MAC address and IP address for your controller below. +// The IP address will be dependent on your local network: +byte mac[] = { + 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED }; +IPAddress ip(192, 168, 1, 177); + +unsigned int localPort = 8888; // local port to listen on + +// An EthernetUDP instance to let us send and receive packets over UDP +EthernetUDP Udp; + +void setup() { + // start the Ethernet and UDP: + Ethernet.begin(mac,ip); + Udp.begin(localPort); +} + +void loop() { + + int packetSize = Udp.parsePacket(); + if(packetSize) + { + Serial.print("Received packet of size "); + Serial.println(packetSize); + Serial.print("From IP : "); + + IPAddress remote = Udp.remoteIP(); + //print out the remote connection's IP address + Serial.print(remote); + + Serial.print(" on port : "); + //print out the remote connection's port + Serial.println(Udp.remotePort()); + } + +} + + +``` + +### `UDP.remotePort()` + +#### Description +Gets the port of the remote UDP connection. + +This function must be called after UDP.parsePacket(). + + +#### Syntax + +``` +UDP.remotePort(); +``` + +#### Parameters +None + +#### Returns +- int : the port of the UDP connection to a remote host + +#### Example + +``` +#include +#include +#include + +// Enter a MAC address and IP address for your controller below. +// The IP address will be dependent on your local network: +byte mac[] = { + 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED }; +IPAddress ip(192, 168, 1, 177); + +unsigned int localPort = 8888; // local port to listen on + +// An EthernetUDP instance to let us send and receive packets over UDP +EthernetUDP Udp; + +char packetBuffer[UDP_TX_PACKET_MAX_SIZE]; //buffer to hold incoming packet, + +void setup() { + // start the Ethernet and UDP: + Ethernet.begin(mac,ip); + Udp.begin(localPort); + +} + +void loop() { + + int packetSize = Udp.parsePacket(); + if(packetSize) + { + Serial.print("Received packet of size "); + Serial.println(packetSize); + Serial.print("From "); + IPAddress remote = Udp.remoteIP(); + for (int i =0; i < 4; i++) + { + Serial.print(remote[i], DEC); + if (i < 3) + { + Serial.print("."); + } + } + Serial.print(", port "); + Serial.println(Udp.remotePort()); + + // read the packet into packetBuffer + Udp.read(packetBuffer,UDP_TX_PACKET_MAX_SIZE); + Serial.println("Contents:"); + Serial.println(packetBuffer); + } +} +``` \ No newline at end of file diff --git a/docs/arduino_mega_ethernet_pins.png b/docs/arduino_mega_ethernet_pins.png new file mode 100644 index 00000000..e35edc2c Binary files /dev/null and b/docs/arduino_mega_ethernet_pins.png differ diff --git a/docs/arduino_uno_ethernet_pins.png b/docs/arduino_uno_ethernet_pins.png new file mode 100644 index 00000000..ae7e520a Binary files /dev/null and b/docs/arduino_uno_ethernet_pins.png differ diff --git a/docs/readme.md b/docs/readme.md new file mode 100644 index 00000000..84d14b2b --- /dev/null +++ b/docs/readme.md @@ -0,0 +1,16 @@ +# Ethernet Library + +This library is designed to work with the Arduino Ethernet Shield, Arduino Ethernet Shield 2, Leonardo Ethernet, and any other W5100/W5200/W5500-based devices. The library allows an Arduino board to connect to the Internet. The board can serve as either a server accepting incoming connections or a client making outgoing ones. The library supports up to eight (W5100 and boards with <= 2 kB SRAM are limited to four) concurrent connections (incoming, outgoing, or a combination). + +The Arduino board communicates with the shield using the SPI bus. This is on digital pins 11, 12, and 13 on the Uno and pins 50, 51, and 52 on the Mega. On both boards, pin 10 is used as SS. On the Mega, the hardware SS pin, 53, is not used to select the Ethernet controller chip, but it must be kept as an output or the SPI interface won't work. + +![Arduino UNO Pin map.](https://raw.githubusercontent.com/arduino-libraries/Ethernet/master/docs/arduino_uno_ethernet_pins.png) + +![Arduino MEGA Pin map.](https://raw.githubusercontent.com/arduino-libraries/Ethernet/master/docs/arduino_mega_ethernet_pins.png) + +To use this library + +``` +#include +#include +``` diff --git a/examples/AdvancedChatServer/AdvancedChatServer.ino b/examples/AdvancedChatServer/AdvancedChatServer.ino index 3b431c88..c97a9589 100644 --- a/examples/AdvancedChatServer/AdvancedChatServer.ino +++ b/examples/AdvancedChatServer/AdvancedChatServer.ino @@ -5,7 +5,7 @@ to all connected clients but the client the message comes from. To use, telnet to your device's IP address and type. You can see the client's input in the serial monitor as well. - Using an Arduino Wiznet Ethernet shield. + Using an Arduino WIZnet Ethernet shield. Circuit: * Ethernet shield attached to pins 10, 11, 12, 13 @@ -42,11 +42,11 @@ EthernetClient clients[8]; void setup() { // You can use Ethernet.init(pin) to configure the CS pin //Ethernet.init(10); // Most Arduino shields - //Ethernet.init(5); // MKR ETH shield + //Ethernet.init(5); // MKR ETH Shield //Ethernet.init(0); // Teensy 2.0 //Ethernet.init(20); // Teensy++ 2.0 - //Ethernet.init(15); // ESP8266 with Adafruit Featherwing Ethernet - //Ethernet.init(33); // ESP32 with Adafruit Featherwing Ethernet + //Ethernet.init(15); // ESP8266 with Adafruit FeatherWing Ethernet + //Ethernet.init(33); // ESP32 with Adafruit FeatherWing Ethernet // initialize the Ethernet device Ethernet.begin(mac, ip, myDns, gateway, subnet); diff --git a/examples/BarometricPressureWebServer/BarometricPressureWebServer.ino b/examples/BarometricPressureWebServer/BarometricPressureWebServer.ino index 56ccc66c..831f17fc 100644 --- a/examples/BarometricPressureWebServer/BarometricPressureWebServer.ino +++ b/examples/BarometricPressureWebServer/BarometricPressureWebServer.ino @@ -1,5 +1,5 @@ /* - SCP1000 Barometric Pressure Sensor Display + SCP1000 Barometric Pressure Sensor Display Serves the output of a Barometric Pressure Sensor as a web page. Uses the SPI library. For details on the sensor, see: @@ -60,11 +60,11 @@ long lastReadingTime = 0; void setup() { // You can use Ethernet.init(pin) to configure the CS pin //Ethernet.init(10); // Most Arduino shields - //Ethernet.init(5); // MKR ETH shield + //Ethernet.init(5); // MKR ETH Shield //Ethernet.init(0); // Teensy 2.0 //Ethernet.init(20); // Teensy++ 2.0 - //Ethernet.init(15); // ESP8266 with Adafruit Featherwing Ethernet - //Ethernet.init(33); // ESP32 with Adafruit Featherwing Ethernet + //Ethernet.init(15); // ESP8266 with Adafruit FeatherWing Ethernet + //Ethernet.init(33); // ESP32 with Adafruit FeatherWing Ethernet // start the SPI library: SPI.begin(); @@ -92,7 +92,7 @@ void setup() { // start listening for clients server.begin(); - // initalize the data ready and chip select pins: + // initialize the data ready and chip select pins: pinMode(dataReadyPin, INPUT); pinMode(chipSelectPin, OUTPUT); @@ -104,7 +104,7 @@ void setup() { // give the sensor and Ethernet shield time to set up: delay(1000); - //Set the sensor to high resolution mode tp start readings: + //Set the sensor to high resolution mode to start readings: writeRegister(0x03, 0x0A); } @@ -131,7 +131,7 @@ void getData() { //Read the temperature data int tempData = readRegister(0x21, 2); - // convert the temperature to celsius and display it: + // convert the temperature to Celsius and display it: temperature = (float)tempData / 20.0; //Read the pressure data highest 3 bits: @@ -155,16 +155,16 @@ void listenForEthernetClients() { EthernetClient client = server.available(); if (client) { Serial.println("Got a client"); - // an http request ends with a blank line + // an HTTP request ends with a blank line bool 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, + // 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 + // send a standard HTTP response header client.println("HTTP/1.1 200 OK"); client.println("Content-Type: text/html"); client.println(); @@ -216,7 +216,7 @@ void writeRegister(byte registerName, byte registerValue) { //Read register from the SCP1000: unsigned int readRegister(byte registerName, int numBytes) { - byte inByte = 0; // incoming from the SPI read + byte inByte = 0; // incoming from the SPI read unsigned int result = 0; // result to return // SCP1000 expects the register name in the upper 6 bits @@ -228,7 +228,7 @@ unsigned int readRegister(byte registerName, int numBytes) { // take the chip select low to select the device: digitalWrite(chipSelectPin, LOW); // send the device the register you want to read: - int command = SPI.transfer(registerName); + SPI.transfer(registerName); // send a value of 0 to read the first byte returned: inByte = SPI.transfer(0x00); diff --git a/examples/ChatServer/ChatServer.ino b/examples/ChatServer/ChatServer.ino index 740d7867..3e280607 100644 --- a/examples/ChatServer/ChatServer.ino +++ b/examples/ChatServer/ChatServer.ino @@ -4,7 +4,7 @@ A simple server that distributes any incoming messages to all connected clients. To use, telnet to your device's IP address and type. You can see the client's input in the serial monitor as well. - Using an Arduino Wiznet Ethernet shield. + Using an Arduino WIZnet Ethernet shield. Circuit: * Ethernet shield attached to pins 10, 11, 12, 13 @@ -37,13 +37,13 @@ bool alreadyConnected = false; // whether or not the client was connected previo void setup() { // You can use Ethernet.init(pin) to configure the CS pin //Ethernet.init(10); // Most Arduino shields - //Ethernet.init(5); // MKR ETH shield + //Ethernet.init(5); // MKR ETH Shield //Ethernet.init(0); // Teensy 2.0 //Ethernet.init(20); // Teensy++ 2.0 - //Ethernet.init(15); // ESP8266 with Adafruit Featherwing Ethernet - //Ethernet.init(33); // ESP32 with Adafruit Featherwing Ethernet + //Ethernet.init(15); // ESP8266 with Adafruit FeatherWing Ethernet + //Ethernet.init(33); // ESP32 with Adafruit FeatherWing Ethernet - // initialize the ethernet device + // initialize the Ethernet device Ethernet.begin(mac, ip, myDns, gateway, subnet); // Open serial communications and wait for port to open: @@ -94,6 +94,3 @@ void loop() { } } } - - - diff --git a/examples/DhcpAddressPrinter/DhcpAddressPrinter.ino b/examples/DhcpAddressPrinter/DhcpAddressPrinter.ino index e40cdfea..612106f9 100644 --- a/examples/DhcpAddressPrinter/DhcpAddressPrinter.ino +++ b/examples/DhcpAddressPrinter/DhcpAddressPrinter.ino @@ -3,7 +3,7 @@ This sketch uses the DHCP extensions to the Ethernet library to get an IP address via DHCP and print the address obtained. - using an Arduino Wiznet Ethernet shield. + using an Arduino WIZnet Ethernet shield. Circuit: Ethernet shield attached to pins 10, 11, 12, 13 @@ -22,17 +22,17 @@ // Enter a MAC address for your controller below. // Newer Ethernet shields have a MAC address printed on a sticker on the shield byte mac[] = { - 0x00, 0xAA, 0xBB, 0xCC, 0xDE, 0x02 + 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED }; void setup() { // You can use Ethernet.init(pin) to configure the CS pin //Ethernet.init(10); // Most Arduino shields - //Ethernet.init(5); // MKR ETH shield + //Ethernet.init(5); // MKR ETH Shield //Ethernet.init(0); // Teensy 2.0 //Ethernet.init(20); // Teensy++ 2.0 - //Ethernet.init(15); // ESP8266 with Adafruit Featherwing Ethernet - //Ethernet.init(33); // ESP32 with Adafruit Featherwing Ethernet + //Ethernet.init(15); // ESP8266 with Adafruit FeatherWing Ethernet + //Ethernet.init(33); // ESP32 with Adafruit FeatherWing Ethernet // Open serial communications and wait for port to open: Serial.begin(9600); @@ -92,4 +92,3 @@ void loop() { break; } } - diff --git a/examples/DhcpChatServer/DhcpChatServer.ino b/examples/DhcpChatServer/DhcpChatServer.ino index f4489d61..01cd8140 100644 --- a/examples/DhcpChatServer/DhcpChatServer.ino +++ b/examples/DhcpChatServer/DhcpChatServer.ino @@ -1,10 +1,10 @@ /* - DHCP Chat Server + DHCP Chat Server A simple server that distributes any incoming messages to all connected clients. To use, telnet to your device's IP address and type. You can see the client's input in the serial monitor as well. - Using an Arduino Wiznet Ethernet shield. + Using an Arduino WIZnet Ethernet shield. THis version attempts to get an IP address using DHCP @@ -27,7 +27,7 @@ // The IP address will be dependent on your local network. // gateway and subnet are optional: byte mac[] = { - 0x00, 0xAA, 0xBB, 0xCC, 0xDE, 0x02 + 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED }; IPAddress ip(192, 168, 1, 177); IPAddress myDns(192, 168, 1, 1); @@ -41,11 +41,11 @@ bool gotAMessage = false; // whether or not you got a message from the client ye void setup() { // You can use Ethernet.init(pin) to configure the CS pin //Ethernet.init(10); // Most Arduino shields - //Ethernet.init(5); // MKR ETH shield + //Ethernet.init(5); // MKR ETH Shield //Ethernet.init(0); // Teensy 2.0 //Ethernet.init(20); // Teensy++ 2.0 - //Ethernet.init(15); // ESP8266 with Adafruit Featherwing Ethernet - //Ethernet.init(33); // ESP32 with Adafruit Featherwing Ethernet + //Ethernet.init(15); // ESP8266 with Adafruit FeatherWing Ethernet + //Ethernet.init(33); // ESP32 with Adafruit FeatherWing Ethernet // Open serial communications and wait for port to open: Serial.begin(9600); @@ -99,4 +99,3 @@ void loop() { Ethernet.maintain(); } } - diff --git a/examples/LinkStatus/LinkStatus.ino b/examples/LinkStatus/LinkStatus.ino index af62ebbe..84651d09 100644 --- a/examples/LinkStatus/LinkStatus.ino +++ b/examples/LinkStatus/LinkStatus.ino @@ -1,11 +1,12 @@ /* Link Status - This sketch prints the ethernet link status. When the - ethernet cable is connected the link status should go to "ON". - NOTE: Only WizNet W5200 and W5500 are capable of reporting + + This sketch prints the Ethernet link status. When the + Ethernet cable is connected the link status should go to "ON". + NOTE: Only WIZnet W5200 and W5500 are capable of reporting the link status. W5100 will report "Unknown". Hardware: - - Ethernet shield or equivalent board/shield with WizNet 5200/5500 + - Ethernet shield or equivalent board/shield with WIZnet W5200/W5500 Written by Cristian Maglie This example is public domain. */ @@ -16,11 +17,11 @@ void setup() { // You can use Ethernet.init(pin) to configure the CS pin //Ethernet.init(10); // Most Arduino shields - //Ethernet.init(5); // MKR ETH shield + //Ethernet.init(5); // MKR ETH Shield //Ethernet.init(0); // Teensy 2.0 //Ethernet.init(20); // Teensy++ 2.0 - //Ethernet.init(15); // ESP8266 with Adafruit Featherwing Ethernet - //Ethernet.init(33); // ESP32 with Adafruit Featherwing Ethernet + //Ethernet.init(15); // ESP8266 with Adafruit FeatherWing Ethernet + //Ethernet.init(33); // ESP32 with Adafruit FeatherWing Ethernet Serial.begin(9600); } diff --git a/examples/PagerServer/PagerServer.ino b/examples/PagerServer/PagerServer.ino new file mode 100644 index 00000000..e17ae6ed --- /dev/null +++ b/examples/PagerServer/PagerServer.ino @@ -0,0 +1,71 @@ +/* + Pager Server + + A simple server that echoes any incoming messages to all + connected clients. Connect two or more telnet sessions + to see how server.available() and server.print() works. + + created in September 2020 for the Ethernet library + by Juraj Andrassy https://github.com/jandrassy + +*/ +#include + +// Enter a MAC address for your controller below. +// Newer Ethernet shields have a MAC address printed on a sticker on the shield +byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED }; + +// Set the static IP address to use if the DHCP fails to assign +IPAddress ip(192, 168, 0, 177); + +EthernetServer server(2323); + +void setup() { + + Serial.begin(9600); + while (!Serial); + + // start the Ethernet connection: + Serial.println("Initialize Ethernet with DHCP:"); + if (Ethernet.begin(mac) == 0) { + Serial.println("Failed to configure Ethernet using DHCP"); + // Check for Ethernet hardware present + if (Ethernet.hardwareStatus() == EthernetNoHardware) { + Serial.println("Ethernet shield was not found. Sorry, can't run without hardware. :("); + while (true) { + delay(1); // do nothing, no point running without Ethernet hardware + } + } + if (Ethernet.linkStatus() == LinkOFF) { + Serial.println("Ethernet cable is not connected."); + } + // try to configure using IP address instead of DHCP: + Ethernet.begin(mac, ip); + } else { + Serial.print(" DHCP assigned IP "); + Serial.println(Ethernet.localIP()); + } + + server.begin(); + + IPAddress ip = Ethernet.localIP(); + Serial.println(); + Serial.print("To access the server, connect with Telnet client to "); + Serial.print(ip); + Serial.println(" 2323"); +} + +void loop() { + + EthernetClient client = server.available(); // returns first client which has data to read or a 'false' client + if (client) { // client is true only if it is connected and has data to read + String s = client.readStringUntil('\n'); // read the message incoming from one of the clients + s.trim(); // trim eventual \r + Serial.println(s); // print the message to Serial Monitor + client.print("echo: "); // this is only for the sending client + server.println(s); // send the message to all connected clients +#ifndef ARDUINO_ARCH_SAM + server.flush(); // flush the buffers +#endif /* !defined(ARDUINO_ARCH_SAM) */ + } +} diff --git a/examples/TelnetClient/TelnetClient.ino b/examples/TelnetClient/TelnetClient.ino index 85386b5f..ff554a5c 100644 --- a/examples/TelnetClient/TelnetClient.ino +++ b/examples/TelnetClient/TelnetClient.ino @@ -1,13 +1,13 @@ /* - Telnet client + Telnet client - This sketch connects to a a telnet server (http://www.google.com) - using an Arduino Wiznet Ethernet shield. You'll need a telnet server + This sketch connects to a telnet server (http://www.google.com) + using an Arduino WIZnet Ethernet shield. You'll need a telnet server to test this with. - Processing's ChatServer example (part of the network library) works well, + Processing's ChatServer example (part of the Network library) works well, running on port 10002. It can be found as part of the examples in the Processing application, available at - http://processing.org/ + https://processing.org/ Circuit: * Ethernet shield attached to pins 10, 11, 12, 13 @@ -39,11 +39,11 @@ EthernetClient client; void setup() { // You can use Ethernet.init(pin) to configure the CS pin //Ethernet.init(10); // Most Arduino shields - //Ethernet.init(5); // MKR ETH shield + //Ethernet.init(5); // MKR ETH Shield //Ethernet.init(0); // Teensy 2.0 //Ethernet.init(20); // Teensy++ 2.0 - //Ethernet.init(15); // ESP8266 with Adafruit Featherwing Ethernet - //Ethernet.init(33); // ESP32 with Adafruit Featherwing Ethernet + //Ethernet.init(15); // ESP8266 with Adafruit FeatherWing Ethernet + //Ethernet.init(33); // ESP32 with Adafruit FeatherWing Ethernet // start the Ethernet connection: Ethernet.begin(mac, ip); @@ -107,7 +107,3 @@ void loop() { } } } - - - - diff --git a/examples/UDPSendReceiveString/UDPSendReceiveString.ino b/examples/UDPSendReceiveString/UDPSendReceiveString.ino index 0c76b022..3995b331 100644 --- a/examples/UDPSendReceiveString/UDPSendReceiveString.ino +++ b/examples/UDPSendReceiveString/UDPSendReceiveString.ino @@ -1,10 +1,11 @@ /* - UDPSendReceiveString: + UDPSendReceiveString + This sketch receives UDP message strings, prints them to the serial port and sends an "acknowledge" string back to the sender A Processing sketch is included at the end of file that can be used to send - and received messages for testing with a computer. + and receive messages for testing with a computer. created 21 Aug 2010 by Michael Margolis @@ -35,11 +36,11 @@ EthernetUDP Udp; void setup() { // You can use Ethernet.init(pin) to configure the CS pin //Ethernet.init(10); // Most Arduino shields - //Ethernet.init(5); // MKR ETH shield + //Ethernet.init(5); // MKR ETH Shield //Ethernet.init(0); // Teensy 2.0 //Ethernet.init(20); // Teensy++ 2.0 - //Ethernet.init(15); // ESP8266 with Adafruit Featherwing Ethernet - //Ethernet.init(33); // ESP32 with Adafruit Featherwing Ethernet + //Ethernet.init(15); // ESP8266 with Adafruit FeatherWing Ethernet + //Ethernet.init(33); // ESP32 with Adafruit FeatherWing Ethernet // start the Ethernet Ethernet.begin(mac, ip); @@ -82,7 +83,7 @@ void loop() { Serial.print(", port "); Serial.println(Udp.remotePort()); - // read the packet into packetBufffer + // read the packet into packetBuffer Udp.read(packetBuffer, UDP_TX_PACKET_MAX_SIZE); Serial.println("Contents:"); Serial.println(packetBuffer); @@ -135,5 +136,3 @@ void loop() { println(); } */ - - diff --git a/examples/UdpNtpClient/UdpNtpClient.ino b/examples/UdpNtpClient/UdpNtpClient.ino index ec52717d..1455b40d 100644 --- a/examples/UdpNtpClient/UdpNtpClient.ino +++ b/examples/UdpNtpClient/UdpNtpClient.ino @@ -1,11 +1,10 @@ /* - Udp NTP Client Get the time from a Network Time Protocol (NTP) time server Demonstrates use of UDP sendPacket and ReceivePacket For more on NTP time servers and the messages needed to communicate with them, - see http://en.wikipedia.org/wiki/Network_Time_Protocol + see https://en.wikipedia.org/wiki/Network_Time_Protocol created 4 Sep 2010 by Michael Margolis @@ -42,11 +41,11 @@ EthernetUDP Udp; void setup() { // You can use Ethernet.init(pin) to configure the CS pin //Ethernet.init(10); // Most Arduino shields - //Ethernet.init(5); // MKR ETH shield + //Ethernet.init(5); // MKR ETH Shield //Ethernet.init(0); // Teensy 2.0 //Ethernet.init(20); // Teensy++ 2.0 - //Ethernet.init(15); // ESP8266 with Adafruit Featherwing Ethernet - //Ethernet.init(33); // ESP32 with Adafruit Featherwing Ethernet + //Ethernet.init(15); // ESP8266 with Adafruit FeatherWing Ethernet + //Ethernet.init(33); // ESP32 with Adafruit FeatherWing Ethernet // Open serial communications and wait for port to open: Serial.begin(9600); @@ -144,13 +143,3 @@ void sendNTPpacket(const char * address) { Udp.write(packetBuffer, NTP_PACKET_SIZE); Udp.endPacket(); } - - - - - - - - - - diff --git a/examples/WebClient/WebClient.ino b/examples/WebClient/WebClient.ino index 45e01eed..f4a5d02a 100644 --- a/examples/WebClient/WebClient.ino +++ b/examples/WebClient/WebClient.ino @@ -1,8 +1,8 @@ /* - Web client + Web client This sketch connects to a website (http://www.google.com) - using an Arduino Wiznet Ethernet shield. + using an Arduino WIZnet Ethernet shield. Circuit: * Ethernet shield attached to pins 10, 11, 12, 13 @@ -43,11 +43,11 @@ bool printWebData = true; // set to false for better speed measurement void setup() { // You can use Ethernet.init(pin) to configure the CS pin //Ethernet.init(10); // Most Arduino shields - //Ethernet.init(5); // MKR ETH shield + //Ethernet.init(5); // MKR ETH Shield //Ethernet.init(0); // Teensy 2.0 //Ethernet.init(20); // Teensy++ 2.0 - //Ethernet.init(15); // ESP8266 with Adafruit Featherwing Ethernet - //Ethernet.init(33); // ESP32 with Adafruit Featherwing Ethernet + //Ethernet.init(15); // ESP8266 with Adafruit FeatherWing Ethernet + //Ethernet.init(33); // ESP32 with Adafruit FeatherWing Ethernet // Open serial communications and wait for port to open: Serial.begin(9600); @@ -69,7 +69,7 @@ void setup() { if (Ethernet.linkStatus() == LinkOFF) { Serial.println("Ethernet cable is not connected."); } - // try to congifure using IP address instead of DHCP: + // try to configure using IP address instead of DHCP: Ethernet.begin(mac, ip, myDns); } else { Serial.print(" DHCP assigned IP "); @@ -134,4 +134,3 @@ void loop() { } } } - diff --git a/examples/WebClientRepeating/WebClientRepeating.ino b/examples/WebClientRepeating/WebClientRepeating.ino index 6607f438..1fb11e10 100644 --- a/examples/WebClientRepeating/WebClientRepeating.ino +++ b/examples/WebClientRepeating/WebClientRepeating.ino @@ -1,10 +1,10 @@ /* - Repeating Web client + Repeating Web client - This sketch connects to a a web server and makes a request - using a Wiznet Ethernet shield. You can use the Arduino Ethernet shield, or + This sketch connects to a web server and makes a request + using a WIZnet Ethernet shield. You can use the Arduino Ethernet Shield, or the Adafruit Ethernet shield, either one will work, as long as it's got - a Wiznet Ethernet module on board. + a WIZnet Ethernet module on board. This example uses DNS, by assigning the Ethernet client with a MAC address, IP address, and DNS address. @@ -17,7 +17,7 @@ modified 21 Jan 2014 by Federico Vanzati - http://www.arduino.cc/en/Tutorial/WebClientRepeating + https://www.arduino.cc/en/Tutorial/WebClientRepeating This code is in the public domain. */ @@ -25,7 +25,7 @@ #include #include -// assign a MAC address for the ethernet controller. +// assign a MAC address for the Ethernet controller. // fill in your address here: byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED @@ -46,11 +46,11 @@ const unsigned long postingInterval = 10*1000; // delay between updates, in mil void setup() { // You can use Ethernet.init(pin) to configure the CS pin //Ethernet.init(10); // Most Arduino shields - //Ethernet.init(5); // MKR ETH shield + //Ethernet.init(5); // MKR ETH Shield //Ethernet.init(0); // Teensy 2.0 //Ethernet.init(20); // Teensy++ 2.0 - //Ethernet.init(15); // ESP8266 with Adafruit Featherwing Ethernet - //Ethernet.init(33); // ESP32 with Adafruit Featherwing Ethernet + //Ethernet.init(15); // ESP8266 with Adafruit FeatherWing Ethernet + //Ethernet.init(33); // ESP32 with Adafruit FeatherWing Ethernet // start serial port: Serial.begin(9600); @@ -72,7 +72,7 @@ void setup() { if (Ethernet.linkStatus() == LinkOFF) { Serial.println("Ethernet cable is not connected."); } - // try to congifure using IP address instead of DHCP: + // try to configure using IP address instead of DHCP: Ethernet.begin(mac, ip, myDns); Serial.print("My IP address: "); Serial.println(Ethernet.localIP()); @@ -104,7 +104,7 @@ void loop() { // this method makes a HTTP connection to the server: void httpRequest() { // close any connection before send a new request. - // This will free the socket on the WiFi shield + // This will free the socket on the Ethernet shield client.stop(); // if there's a successful connection: @@ -124,7 +124,3 @@ void httpRequest() { Serial.println("connection failed"); } } - - - - diff --git a/examples/WebServer/WebServer.ino b/examples/WebServer/WebServer.ino index 06a85576..f3929d2d 100644 --- a/examples/WebServer/WebServer.ino +++ b/examples/WebServer/WebServer.ino @@ -1,8 +1,8 @@ /* - Web Server + Web Server A simple web server that shows the value of the analog input pins. - using an Arduino Wiznet Ethernet shield. + using an Arduino WIZnet Ethernet shield. Circuit: * Ethernet shield attached to pins 10, 11, 12, 13 @@ -35,11 +35,11 @@ EthernetServer server(80); void setup() { // You can use Ethernet.init(pin) to configure the CS pin //Ethernet.init(10); // Most Arduino shields - //Ethernet.init(5); // MKR ETH shield + //Ethernet.init(5); // MKR ETH Shield //Ethernet.init(0); // Teensy 2.0 //Ethernet.init(20); // Teensy++ 2.0 - //Ethernet.init(15); // ESP8266 with Adafruit Featherwing Ethernet - //Ethernet.init(33); // ESP32 with Adafruit Featherwing Ethernet + //Ethernet.init(15); // ESP8266 with Adafruit FeatherWing Ethernet + //Ethernet.init(33); // ESP32 with Adafruit FeatherWing Ethernet // Open serial communications and wait for port to open: Serial.begin(9600); @@ -74,17 +74,17 @@ void loop() { EthernetClient client = server.available(); if (client) { Serial.println("new client"); - // an http request ends with a blank line + // an HTTP request ends with a blank line bool currentLineIsBlank = true; while (client.connected()) { if (client.available()) { char c = client.read(); Serial.write(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, + // 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 + // send a standard HTTP response header client.println("HTTP/1.1 200 OK"); client.println("Content-Type: text/html"); client.println("Connection: close"); // the connection will be closed after completion of the response @@ -120,4 +120,3 @@ void loop() { Serial.println("client disconnected"); } } - diff --git a/library.properties b/library.properties index de68a94f..f3f36166 100644 --- a/library.properties +++ b/library.properties @@ -1,10 +1,10 @@ name=Ethernet -version=2.0.0 +version=2.0.2 author=Various (see AUTHORS file for details) -maintainer=Paul Stoffregen , Arduino +maintainer=Arduino sentence=Enables network connection (local and Internet) using the Arduino Ethernet Board or Shield. -paragraph=With this library you can use the Arduino Ethernet (shield or board) to connect to Internet. The library provides both Client and server functionalities. The library permits you to connect to a local network also with DHCP and to resolve DNS. +paragraph=With this library you can use the Arduino Ethernet (shield or board) to connect to Internet. The library provides both client and server functionalities. The library permits you to connect to a local network also with DHCP and to resolve DNS. category=Communication -url=http://www.arduino.cc/en/Reference/Ethernet +url=https://www.arduino.cc/en/Reference/Ethernet architectures=* includes=Ethernet.h diff --git a/src/Dns.cpp b/src/Dns.cpp index 2cad2d09..787ad2f7 100644 --- a/src/Dns.cpp +++ b/src/Dns.cpp @@ -1,4 +1,4 @@ -// Arduino DNS client for WizNet5100-based Ethernet shield +// Arduino DNS client for WIZnet W5100-based Ethernet shield // (c) Copyright 2009-2010 MCQN Ltd. // Released under Apache License, version 2.0 @@ -336,7 +336,7 @@ uint16_t DNSClient::ProcessResponse(uint16_t aTimeout, IPAddress& aAddress) iUdp.flush(); // FIXME return -9;//INVALID_RESPONSE; } - // FIXME: seeems to lock up here on ESP8266, but why?? + // FIXME: seems to lock up here on ESP8266, but why?? iUdp.read(aAddress.raw_address(), 4); return SUCCESS; } else { @@ -351,4 +351,3 @@ uint16_t DNSClient::ProcessResponse(uint16_t aTimeout, IPAddress& aAddress) // If we get here then we haven't found an answer return -10; //INVALID_RESPONSE; } - diff --git a/src/Dns.h b/src/Dns.h index 5f5b30f5..58f9d2c5 100644 --- a/src/Dns.h +++ b/src/Dns.h @@ -1,4 +1,4 @@ -// Arduino DNS client for WizNet5100-based Ethernet shield +// Arduino DNS client for WIZnet W5100-based Ethernet shield // (c) Copyright 2009-2010 MCQN Ltd. // Released under Apache License, version 2.0 diff --git a/src/Ethernet.cpp b/src/Ethernet.cpp index 1914c67d..5fd69719 100644 --- a/src/Ethernet.cpp +++ b/src/Ethernet.cpp @@ -77,15 +77,9 @@ void EthernetClass::begin(uint8_t *mac, IPAddress ip, IPAddress dns, IPAddress g { if (W5500.init() == 0) return; W5500.setMACAddress(mac); -#if ARDUINO > 106 || TEENSYDUINO > 121 W5500.setIPAddress(ip._address.bytes); W5500.setGatewayIp(gateway._address.bytes); W5500.setSubnetMask(subnet._address.bytes); -#else - W5500.setIPAddress(ip._address); - W5500.setGatewayIp(gateway._address); - W5500.setSubnetMask(subnet._address); -#endif _dnsServerAddress = dns; } //----------------------------------------------------------------------------- diff --git a/src/Ethernet.h b/src/Ethernet.h index 0cea180d..abe1c17d 100644 --- a/src/Ethernet.h +++ b/src/Ethernet.h @@ -39,12 +39,12 @@ #define MAX_SOCK_NUM 8 #endif -// By default, each socket uses 2K buffers inside the Wiznet chip. If +// By default, each socket uses 2K buffers inside the WIZnet chip. If // MAX_SOCK_NUM is set to fewer than the chip's maximum, uncommenting -// this will use larger buffers within the Wiznet chip. Large buffers +// this will use larger buffers within the WIZnet chip. Large buffers // can really help with UDP protocols like Artnet. In theory larger // buffers should allow faster TCP over high-latency links, but this -// does not always seem to work in practice (maybe Wiznet bugs?) +// does not always seem to work in practice (maybe WIZnet bugs?) //#define ETHERNET_LARGE_BUFFERS @@ -77,7 +77,7 @@ class EthernetClass { static int maintain(); static EthernetLinkStatus linkStatus(); - // Manaul configuration + // Manual configuration static void begin(uint8_t *mac, IPAddress ip); static void begin(uint8_t *mac, IPAddress ip, IPAddress dns); static void begin(uint8_t *mac, IPAddress ip, IPAddress dns, IPAddress gateway); @@ -205,8 +205,9 @@ class EthernetUDP : public UDP { //----------------------------------------------------------------------------- class EthernetClient : public Client { public: - EthernetClient() : sockindex(MAX_SOCK_NUM), _timeout(1000) { } - EthernetClient(uint8_t s) : sockindex(s), _timeout(1000) { } + EthernetClient() : _sockindex(MAX_SOCK_NUM), _timeout(1000) { } + EthernetClient(uint8_t s) : _sockindex(s), _timeout(1000) { } + virtual ~EthernetClient() {}; uint8_t status(); virtual int connect(IPAddress ip, uint16_t port); @@ -221,12 +222,12 @@ class EthernetClient : public Client { virtual void flush(); virtual void stop(); virtual uint8_t connected(); - virtual operator bool() { return sockindex < MAX_SOCK_NUM; } + virtual operator bool() { return _sockindex < MAX_SOCK_NUM; } virtual bool operator==(const bool value) { return bool() == value; } virtual bool operator!=(const bool value) { return bool() != value; } virtual bool operator==(const EthernetClient&); virtual bool operator!=(const EthernetClient& rhs) { return !this->operator==(rhs); } - uint8_t getSocketNumber() const { return sockindex; } + uint8_t getSocketNumber() const { return _sockindex; } virtual uint16_t localPort(); virtual IPAddress remoteIP(); virtual void getRemoteIP(IPAddress ip) { ip = remoteIP(); } @@ -238,7 +239,7 @@ class EthernetClient : public Client { using Print::write; private: - uint8_t sockindex; // MAX_SOCK_NUM means client not in use + uint8_t _sockindex; // MAX_SOCK_NUM means client not in use uint16_t _timeout; }; diff --git a/src/EthernetClient.cpp b/src/EthernetClient.cpp index 5e6905dc..f7901c3c 100644 --- a/src/EthernetClient.cpp +++ b/src/EthernetClient.cpp @@ -28,11 +28,11 @@ int EthernetClient::connect(const char * host, uint16_t port) DNSClient dns; // Look up the host first IPAddress remote_addr; - if (sockindex < MAX_SOCK_NUM) { - if (Ethernet.socketStatus(sockindex) != SnSR::CLOSED) { - Ethernet.socketDisconnect(sockindex); // TODO: should we call stop()? + if (_sockindex < MAX_SOCK_NUM) { + if (Ethernet.socketStatus(_sockindex) != SnSR::CLOSED) { + Ethernet.socketDisconnect(_sockindex); // TODO: should we call stop()? } - sockindex = MAX_SOCK_NUM; + _sockindex = MAX_SOCK_NUM; } dns.begin(Ethernet.dnsServerIP()); if (!dns.getHostByName(host, remote_addr)) return 0; // TODO: use _timeout @@ -41,38 +41,38 @@ int EthernetClient::connect(const char * host, uint16_t port) //----------------------------------------------------------------------------- int EthernetClient::connect(IPAddress ip, uint16_t port) { - if (sockindex < MAX_SOCK_NUM) { - if (Ethernet.socketStatus(sockindex) != SnSR::CLOSED) { - Ethernet.socketDisconnect(sockindex); // TODO: should we call stop()? + if (_sockindex < MAX_SOCK_NUM) { + if (Ethernet.socketStatus(_sockindex) != SnSR::CLOSED) { + Ethernet.socketDisconnect(_sockindex); // TODO: should we call stop()? } - sockindex = MAX_SOCK_NUM; + _sockindex = MAX_SOCK_NUM; } #if defined(ESP8266) || defined(ESP32) if (ip == IPAddress((uint32_t)0) || ip == IPAddress(0xFFFFFFFFul)) return 0; #else if (ip == IPAddress(0ul) || ip == IPAddress(0xFFFFFFFFul)) return 0; #endif - sockindex = Ethernet.socketBegin(SnMR::TCP, 0); - if (sockindex >= MAX_SOCK_NUM) return 0; - Ethernet.socketConnect(sockindex, rawIPAddress(ip), port); + _sockindex = Ethernet.socketBegin(SnMR::TCP, 0); + if (_sockindex >= MAX_SOCK_NUM) return 0; + Ethernet.socketConnect(_sockindex, rawIPAddress(ip), port); uint32_t start = millis(); while (1) { - uint8_t stat = Ethernet.socketStatus(sockindex); + uint8_t stat = Ethernet.socketStatus(_sockindex); if (stat == SnSR::ESTABLISHED) return 1; if (stat == SnSR::CLOSE_WAIT) return 1; if (stat == SnSR::CLOSED) return 0; if (millis() - start > _timeout) break; delay(1); } - Ethernet.socketClose(sockindex); - sockindex = MAX_SOCK_NUM; + Ethernet.socketClose(_sockindex); + _sockindex = MAX_SOCK_NUM; return 0; } //----------------------------------------------------------------------------- int EthernetClient::availableForWrite(void) { - if (sockindex >= MAX_SOCK_NUM) return 0; - return Ethernet.socketSendAvailable(sockindex); + if (_sockindex >= MAX_SOCK_NUM) return 0; + return Ethernet.socketSendAvailable(_sockindex); } //----------------------------------------------------------------------------- size_t EthernetClient::write(uint8_t b) @@ -82,48 +82,48 @@ size_t EthernetClient::write(uint8_t b) //----------------------------------------------------------------------------- size_t EthernetClient::write(const uint8_t *buf, size_t size) { - if (sockindex >= MAX_SOCK_NUM) return 0; - if (Ethernet.socketSend(sockindex, buf, size)) return size; + if (_sockindex >= MAX_SOCK_NUM) return 0; + if (Ethernet.socketSend(_sockindex, buf, size)) return size; setWriteError(); return 0; } //----------------------------------------------------------------------------- int EthernetClient::available() { - if (sockindex >= MAX_SOCK_NUM) return 0; - return Ethernet.socketRecvAvailable(sockindex); - // TODO: do the Wiznet chips automatically retransmit TCP ACK + if (_sockindex >= MAX_SOCK_NUM) return 0; + return Ethernet.socketRecvAvailable(_sockindex); + // TODO: do the WIZnet chips automatically retransmit TCP ACK // packets if they are lost by the network? Someday this should // be checked by a man-in-the-middle test which discards certain // packets. If ACKs aren't resent, we would need to check for // returning 0 here and after a timeout do another Sock_RECV - // command to cause the Wiznet chip to resend the ACK packet. + // command to cause the WIZnet chip to resend the ACK packet. } //----------------------------------------------------------------------------- int EthernetClient::read(uint8_t *buf, size_t size) { - if (sockindex >= MAX_SOCK_NUM) return 0; - return Ethernet.socketRecv(sockindex, buf, size); + if (_sockindex >= MAX_SOCK_NUM) return 0; + return Ethernet.socketRecv(_sockindex, buf, size); } //----------------------------------------------------------------------------- int EthernetClient::peek() { - if (sockindex >= MAX_SOCK_NUM) return -1; + if (_sockindex >= MAX_SOCK_NUM) return -1; if (!available()) return -1; - return Ethernet.socketPeek(sockindex); + return Ethernet.socketPeek(_sockindex); } //----------------------------------------------------------------------------- int EthernetClient::read() { uint8_t b; - if (Ethernet.socketRecv(sockindex, &b, 1) > 0) return b; + if (Ethernet.socketRecv(_sockindex, &b, 1) > 0) return b; return -1; } //----------------------------------------------------------------------------- void EthernetClient::flush() { - while (sockindex < MAX_SOCK_NUM) { - uint8_t stat = Ethernet.socketStatus(sockindex); + while (_sockindex < MAX_SOCK_NUM) { + uint8_t stat = Ethernet.socketStatus(_sockindex); if (stat != SnSR::ESTABLISHED && stat != SnSR::CLOSE_WAIT) return; if (Ethernet.socketSendAvailable(sockindex) >= W5500.SSIZE) return; } @@ -131,48 +131,48 @@ void EthernetClient::flush() //----------------------------------------------------------------------------- void EthernetClient::stop() { - if (sockindex >= MAX_SOCK_NUM) return; + if (_sockindex >= MAX_SOCK_NUM) return; // attempt to close the connection gracefully (send a FIN to other side) - Ethernet.socketDisconnect(sockindex); + Ethernet.socketDisconnect(_sockindex); unsigned long start = millis(); // wait up to a second for the connection to close do { - if (Ethernet.socketStatus(sockindex) == SnSR::CLOSED) { - sockindex = MAX_SOCK_NUM; + if (Ethernet.socketStatus(_sockindex) == SnSR::CLOSED) { + _sockindex = MAX_SOCK_NUM; return; // exit the loop } delay(1); } while (millis() - start < _timeout); // if it hasn't closed, close it forcefully - Ethernet.socketClose(sockindex); - sockindex = MAX_SOCK_NUM; + Ethernet.socketClose(_sockindex); + _sockindex = MAX_SOCK_NUM; } //----------------------------------------------------------------------------- uint8_t EthernetClient::connected() { - if (sockindex >= MAX_SOCK_NUM) return 0; + if (_sockindex >= MAX_SOCK_NUM) return 0; - uint8_t s = Ethernet.socketStatus(sockindex); + uint8_t s = Ethernet.socketStatus(_sockindex); return !(s == SnSR::LISTEN || s == SnSR::CLOSED || s == SnSR::FIN_WAIT || (s == SnSR::CLOSE_WAIT && !available())); } //----------------------------------------------------------------------------- uint8_t EthernetClient::status() { - if (sockindex >= MAX_SOCK_NUM) return SnSR::CLOSED; - return Ethernet.socketStatus(sockindex); + if (_sockindex >= MAX_SOCK_NUM) return SnSR::CLOSED; + return Ethernet.socketStatus(_sockindex); } //----------------------------------------------------------------------------- // the next function allows us to use the client returned by // EthernetServer::available() as the condition in an if-statement. bool EthernetClient::operator==(const EthernetClient& rhs) { - if (sockindex != rhs.sockindex) return false; - if (sockindex >= MAX_SOCK_NUM) return false; - if (rhs.sockindex >= MAX_SOCK_NUM) return false; + if (_sockindex != rhs._sockindex) return false; + if (_sockindex >= MAX_SOCK_NUM) return false; + if (rhs._sockindex >= MAX_SOCK_NUM) return false; return true; } //----------------------------------------------------------------------------- @@ -186,10 +186,10 @@ uint16_t EthernetClient::localPort() } //----------------------------------------------------------------------------- // https://github.com/per1234/EthernetMod -// returns the remote IP address: http://forum.arduino.cc/index.php?topic=82416.0 +// returns the remote IP address: https://forum.arduino.cc/index.php?topic=82416.0 IPAddress EthernetClient::remoteIP() { - if (sockindex >= MAX_SOCK_NUM) return IPAddress((uint32_t)0); + if (_sockindex >= MAX_SOCK_NUM) return IPAddress((uint32_t)0); uint8_t remoteIParray[4]; W5500.readSnDIPR(sockindex, remoteIParray); return IPAddress(remoteIParray); @@ -203,5 +203,3 @@ uint16_t EthernetClient::remotePort() uint16_t port = W5500.readSnDPORT(sockindex); return port; } - - diff --git a/src/EthernetUdp.cpp b/src/EthernetUdp.cpp index 186c665b..60480d8b 100644 --- a/src/EthernetUdp.cpp +++ b/src/EthernetUdp.cpp @@ -1,5 +1,5 @@ /* - * Udp.cpp: Library to send/receive UDP packets with the Arduino ethernet shield. + * Udp.cpp: Library to send/receive UDP packets with the Arduino Ethernet Shield. * This version only offers minimal wrapping of socket.cpp * Drop Udp.h/.cpp into the Ethernet library directory at hardware/libraries/Ethernet/ * @@ -187,4 +187,3 @@ uint8_t EthernetUDP::beginMulticast(IPAddress ip, uint16_t port) _remaining = 0; return 1; } - diff --git a/src/EthernetUdp.h b/src/EthernetUdp.h index 2438ec93..16bb062e 100644 --- a/src/EthernetUdp.h +++ b/src/EthernetUdp.h @@ -1,5 +1,5 @@ /* - * Udp.cpp: Library to send/receive UDP packets with the Arduino ethernet shield. + * Udp.cpp: Library to send/receive UDP packets with the Arduino Ethernet Shield. * This version only offers minimal wrapping of socket.cpp * Drop Udp.h/.cpp into the Ethernet library directory at hardware/libraries/Ethernet/ * diff --git a/src/socket.cpp b/src/socket.cpp index 59b724b6..de9a40cb 100644 --- a/src/socket.cpp +++ b/src/socket.cpp @@ -459,4 +459,3 @@ bool EthernetClass::socketSendUDP(uint8_t s) /* Sent ok */ return true; } - diff --git a/src/utility/w5500.h b/src/utility/w5500.h index fa930cf1..5704461a 100644 --- a/src/utility/w5500.h +++ b/src/utility/w5500.h @@ -327,13 +327,26 @@ extern W5500Class W5500; #ifndef UTIL_H #define UTIL_H -#define htons(x) ( (((x)<<8)&0xFF00) | (((x)>>8)&0xFF) ) +#ifndef htons +// The host order of the Arduino platform is little endian. +// Sometimes it is desired to convert to big endian (or +// network order) + +// Host to Network short +#define htons(x) ( (((x)&0xFF)<<8) | (((x)>>8)&0xFF) ) + +// Network to Host short #define ntohs(x) htons(x) +// Host to Network long #define htonl(x) ( ((x)<<24 & 0xFF000000UL) | \ ((x)<< 8 & 0x00FF0000UL) | \ ((x)>> 8 & 0x0000FF00UL) | \ ((x)>>24 & 0x000000FFUL) ) + +// Network to Host long #define ntohl(x) htonl(x) +#endif // !defined(htons) + #endif