Skip to content

Create option for setting and getting the hostname #223

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 4 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
77 changes: 77 additions & 0 deletions docs/api.md
Original file line number Diff line number Diff line change
Expand Up @@ -473,6 +473,83 @@ void setup() {
void loop () {}
```

### `Ethernet.setHostName()`

#### Description

Set the hostname of the device. This is used in DHCP requests and responses.


#### Syntax

```
Ethernet.setHostName(hostName)

```

#### Parameters
- hostName: the hostname of the device (const char*)

#### Returns
Nothing

#### Example

```
#include <SPI.h>
#include <Ethernet.h>

byte mac[] = {0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED};
char hostName[] = "NameOfTheDevice";

void setup() {
Ethernet.setHostName(hostName);
Ethernet.begin(mac);
}

void loop () {}
```

### `Ethernet.getHostName()`

#### Description

Get the hostname of the device. This is used in DHCP requests and responses.


#### Syntax

```
Ethernet.getHostName()

```

#### Parameters
none

#### Returns
- hostName: the hostname of the device (const char*)

#### Example

```
#include <SPI.h>
#include <Ethernet.h>

byte mac[] = {0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED};

void setup() {
Ethernet.begin(mac);
const char* hostName = Ethernet.getHostName();

Serial.begin(9600);
Serial.print("Host name: ");
Serial.println(hostName);
}

void loop () {}
```

### `Ethernet.setGatewayIP()`

#### Description
Expand Down
61 changes: 61 additions & 0 deletions examples/SetHostName/SetHostName.ino
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
/*
Set Host Name

This example shows you how to set the host name with the Ethernet library.

Circuit:
* Ethernet shield attached to pins 10, 11, 12, 13

created 28 May 2023
by Attila Herczog
*/

#include <SPI.h>
#include <Ethernet.h>

// 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 };

// Host name to use
char hostName[] = "ExampleHostName";

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
}
Serial.println("Host Name Example");

// Set the Host Name
// Call this function before Ethernet.begin() to set your host name.
Ethernet.setHostName(hostName);

// Start the Ethernet connection and the server:
Ethernet.begin(mac);

// 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.");
}

Serial.print("My IP is: ");
Serial.println(Ethernet.localIP());
Serial.print("My host name is: ");
Serial.println(Ethernet.getHostName());
Serial.println("You can now check your router's DHCP table to see the assigned host name.");
}

void loop() {}
2 changes: 1 addition & 1 deletion library.properties
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
name=Ethernet
version=2.0.2
version=2.0.3
author=Various (see AUTHORS file for details)
maintainer=Arduino <[email protected]>
sentence=Enables network connection (local and Internet) using the Arduino Ethernet Board or Shield.
Expand Down
18 changes: 9 additions & 9 deletions src/Dhcp.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -6,13 +6,14 @@
#include "Dhcp.h"
#include "utility/w5100.h"

int DhcpClass::beginWithDHCP(uint8_t *mac, unsigned long timeout, unsigned long responseTimeout)
int DhcpClass::beginWithDHCP(uint8_t *mac, const char *hostName, unsigned long timeout, unsigned long responseTimeout)
{
_dhcpLeaseTime=0;
_dhcpT1=0;
_dhcpT2=0;
_timeout = timeout;
_responseTimeout = responseTimeout;
_dhcpHostName = hostName;

// zero out _dhcpMacAddr
memset(_dhcpMacAddr, 0, 6);
Expand Down Expand Up @@ -186,17 +187,16 @@ void DhcpClass::send_DHCP_MESSAGE(uint8_t messageType, uint16_t secondsElapsed)
buffer[9] = 0x01;
memcpy(buffer + 10, _dhcpMacAddr, 6);

// OPT - host name
buffer[16] = hostName;
buffer[17] = strlen(HOST_NAME) + 6; // length of hostname + last 3 bytes of mac address
strcpy((char*)&(buffer[18]), HOST_NAME);
_dhcpUdpSocket.write(buffer, 16);

printByte((char*)&(buffer[24]), _dhcpMacAddr[3]);
printByte((char*)&(buffer[26]), _dhcpMacAddr[4]);
printByte((char*)&(buffer[28]), _dhcpMacAddr[5]);
// OPT - host name
buffer[0] = hostName;
uint8_t hostNameLength = strlen(_dhcpHostName);
buffer[1] = hostNameLength;
strcpy((char*)&(buffer[2]), _dhcpHostName);

//put data in W5100 transmit buffer
_dhcpUdpSocket.write(buffer, 30);
_dhcpUdpSocket.write(buffer, hostNameLength + 2);

if (messageType == DHCP_REQUEST) {
buffer[0] = dhcpRequestedIPaddr;
Expand Down
1 change: 0 additions & 1 deletion src/Dhcp.h
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,6 @@
#define MAGIC_COOKIE 0x63825363
#define MAX_DHCP_OPT 16

#define HOST_NAME "WIZnet"
#define DEFAULT_LEASE (900) //default lease time in seconds

#define DHCP_CHECK_NONE (0)
Expand Down
35 changes: 34 additions & 1 deletion src/Ethernet.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,8 @@

IPAddress EthernetClass::_dnsServerAddress;
DhcpClass* EthernetClass::_dhcp = NULL;
bool EthernetClass::_manualHostName = false;
char EthernetClass::_hostName[HOST_NAME_MAX_LEN] = "";

int EthernetClass::begin(uint8_t *mac, unsigned long timeout, unsigned long responseTimeout)
{
Expand All @@ -38,8 +40,13 @@ int EthernetClass::begin(uint8_t *mac, unsigned long timeout, unsigned long resp
W5100.setIPAddress(IPAddress(0,0,0,0).raw_address());
SPI.endTransaction();

// Generate a default host name based on the MAC address if not already set by user
if(!_manualHostName) {
generateDefaultHostName(mac);
}

// Now try to get our config info from a DHCP server
int ret = _dhcp->beginWithDHCP(mac, timeout, responseTimeout);
int ret = _dhcp->beginWithDHCP(mac, _hostName, timeout, responseTimeout);
if (ret == 1) {
// We've successfully found a DHCP server and got our configuration
// info, so set things accordingly
Expand Down Expand Up @@ -224,6 +231,32 @@ void EthernetClass::setRetransmissionCount(uint8_t num)
SPI.endTransaction();
}

void EthernetClass::generateDefaultHostName(uint8_t *mac) {
// Copy the default host name base
strcpy(_hostName, DEFAULT_HOST_NAME);

// Append the last 3 bytes of the MAC (HEX'd)
char macAddrStr[3];
sprintf(macAddrStr, "%02X", mac[3]);
strcat(_hostName, macAddrStr);
sprintf(macAddrStr, "%02X", mac[4]);
strcat(_hostName, macAddrStr);
sprintf(macAddrStr, "%02X", mac[5]);
strcat(_hostName, macAddrStr);
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Could this be reduced to one line?
sprintf_P(_hostName, PSTR("%02X%02X02X"), mac[3], mac[4], mac[5])

PSTR() saves the format string in program memory (Flash) instead of RAM. I haven't tested my suggestion, just thought it may help shrink code size.

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Good idea. I changed a bit on your suggestion to include the default hostname as well.
Works nicely on my setup. I don't know, how memory usage can be tested. the compiler gives the same information in either case:
"Sketch uses 12230 bytes (39%) of program storage space. Maximum is 30720 bytes.
Global variables use 714 bytes of dynamic memory."

Copy link
Contributor

@gudnimg gudnimg May 28, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The report from the Github bot shows change in arduino:avr:mega:

Before:

  • Flash memory: +1574 bytes
  • SRAM: +28 bytes

After:

  • Flash memory: +1482 bytes
  • SRAM: +22 bytes

A very welcome change :)

Now I wonder what is adding over 1KB of memory? 🤔 It seems like a lot.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Could the 1KB increase be explained by the compiler deciding to inline some functions on its own? I've seen that before when LTO is enabled (I'm not sure if that's the case in the default Arduino builds).

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I refactored this again. This time I removed the usage of sprintf, and copied the MAC part on a bit lower level.
Now, I can see much smaller numbers on the "Memory usage change".
Can you check this, please?

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It looks correct to me. 👍

}

void EthernetClass::setHostName(const char *dhcpHost) {
// Copy the host name and ensure it is null terminated
strncpy(_hostName, dhcpHost, HOST_NAME_MAX_LEN);
_hostName[HOST_NAME_MAX_LEN - 1] = '\0';

// Indicate that a host name has been set manually
_manualHostName = true;
}

char* EthernetClass::getHostName() {
return _hostName;
}



Expand Down
11 changes: 10 additions & 1 deletion src/Ethernet.h
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,9 @@
#include "Server.h"
#include "Udp.h"

#define DEFAULT_HOST_NAME "WIZnet"
#define HOST_NAME_MAX_LEN 20 // Max 30 or change the DHCP local buffer size

enum EthernetLinkStatus {
Unknown,
LinkON,
Expand All @@ -75,6 +78,8 @@ class EthernetClass {
private:
static IPAddress _dnsServerAddress;
static DhcpClass* _dhcp;
static char _hostName[HOST_NAME_MAX_LEN];
static bool _manualHostName;
public:
// Initialise the Ethernet shield to use the provided MAC address and
// gain the rest of the configuration through DHCP.
Expand Down Expand Up @@ -104,6 +109,8 @@ class EthernetClass {
void setDnsServerIP(const IPAddress dns_server) { _dnsServerAddress = dns_server; }
void setRetransmissionTimeout(uint16_t milliseconds);
void setRetransmissionCount(uint8_t num);
void setHostName(const char *hostName);
char* getHostName();

friend class EthernetClient;
friend class EthernetServer;
Expand Down Expand Up @@ -142,6 +149,7 @@ class EthernetClass {
static bool socketSendUDP(uint8_t s);
// Initialize the "random" source port number
static void socketPortRand(uint16_t n);
static void generateDefaultHostName(uint8_t *mac);
};

extern EthernetClass Ethernet;
Expand Down Expand Up @@ -275,6 +283,7 @@ class DhcpClass {
uint32_t _dhcpInitialTransactionId;
uint32_t _dhcpTransactionId;
uint8_t _dhcpMacAddr[6];
const char* _dhcpHostName;
#ifdef __arm__
uint8_t _dhcpLocalIp[4] __attribute__((aligned(4)));
uint8_t _dhcpSubnetMask[4] __attribute__((aligned(4)));
Expand Down Expand Up @@ -312,7 +321,7 @@ class DhcpClass {
IPAddress getDhcpServerIp();
IPAddress getDnsServerIp();

int beginWithDHCP(uint8_t *, unsigned long timeout = 60000, unsigned long responseTimeout = 4000);
int beginWithDHCP(uint8_t *, const char *hostName, unsigned long timeout = 60000, unsigned long responseTimeout = 4000);
int checkLease();
};

Expand Down