0
votes

I am currently trying to send UDP datagrams from my Arduino to a server. I researched a bit online and found some code, which helped me to send them via a domain. Which works fine. But in my case I need to send it to a IP address, instead of a domain name (because my server doesn't have a domain). In this case I use the Ethercard library.

#include <EtherCard.h>

static byte mymac[] = { 0x1A,0x2B,0x3C,0x4D,0x5E,0x6F };
byte Ethernet::buffer[700];
static uint32_t timer;

const char website[] PROGMEM = "name.tld";


const int dstPort PROGMEM = 54321;
const int srcPort PROGMEM = 54321;



void setup () {
  Serial.begin(9600);

  // Change 'SS' to your Slave Select pin, if you arn't using the default pin
  if (ether.begin(sizeof Ethernet::buffer, mymac, SS) == 0)
    Serial.println( "Failed to access Ethernet controller");
  if (!ether.dhcpSetup())
    Serial.println("DHCP failed");

  ether.printIp("IP:  ", ether.myip);
  ether.printIp("GW:  ", ether.gwip);
  ether.printIp("DNS: ", ether.dnsip);

  //if (!ether.dnsLookup(website))
  //  Serial.println("DNS failed");

  ether.printIp("SRV: ", ether.hisip);
}

char textToSend[] = "Hello";

void loop () {
    if (millis() > timer) {
      timer = millis() + 5000;
     //static void sendUdp (char *data,uint8_t len,uint16_t sport, uint8_t *dip, uint16_t dport);
     ether.sendUdp(textToSend, sizeof(textToSend), srcPort, ether.hisip, dstPort );
  }
}

This is my code for sending something to a domain.

1

1 Answers

0
votes

I assume you are using this library. https://github.com/njh/EtherCard

The README explains how to send UDP datagrams. You want to use uint8_t parseIp(uint8_t *bytestr, const char *str) to format a destination IP address.

char payload[] = "My UDP message";
uint8_t nSourcePort = 1234;
uint8_t nDestinationPort = 5678;
uint8_t ipDestinationAddress[IP_LEN];
ether.parseIp(ipDestinationAddress, "192.168.0.200");

ether.sendUdp(payload, sizeof(payload), nSourcePort, ipDestinationAddress, nDestinationPort);