【得捷电子Follow me第4期】基础任务二:主控板建立TCPIP或UDP服务器
[复制链接]
测试UDP通信测试,编译环境Arduino IDE。
一、基础任务二内容
基础任务二:主控板建立TCPIP或UDP服务器,局域网PC使用TCPIP或UDP客户端进行连接并发送数据,主控板接收到数据后,送液晶屏显示(没有则通过串口打印显示);通过抓包软件抓取交互报文,展示并分析。(TCP和UDP二选一,或者全都操作)。
二、代码
测试代码
#include <SPI.h>
#include <Ethernet.h>
#include <Dns.h>
#include <EthernetUdp.h>
// 网卡mac地址
byte mac[] = { 0x00, 0x01, 0x00, 0x00, 0x00, 0xFF };
DNSClient dnClient;
EthernetUDP Udp;
IPAddress dstip;
//SOCKET pingSocket = 0;
//char buffer[256];
char packetBuffer[UDP_TX_PACKET_MAX_SIZE]; // buffer to hold incoming packet,
char ReplyBuffer[] = "acknowledged"; // a string to send back
// 静态ip地址、DNS服务、网关、子网掩码
IPAddress ip(192, 168, 1, 205);
IPAddress myDns(192, 168, 1, 1);
IPAddress gateway(192, 168, 1, 1);
IPAddress subnet(255, 255, 255, 0);
unsigned int localPort = 5000; // local port to listen on
void setup() {
// 配置LED
pinMode(LED_BUILTIN, OUTPUT);
// 配置串口
Serial.begin(115200);
while (!Serial) {
; // 等待串口连接
}
// 静态IP设置
Serial.println("Ethernet Begin");
Ethernet.init(17);
Ethernet.begin(mac, ip, myDns, gateway, subnet);
// 输出网卡mac地址、IP地址、子网掩码、DNS、网关
Serial.print("My Mac address: ");
byte macBuffer[6]; // 设置mac地址存储buff
Ethernet.MACAddress(macBuffer); // 读取mac地址
for (byte octet = 0; octet < 6; octet++) {
Serial.print(macBuffer[octet], HEX);
if (octet < 5) {
Serial.print('-');
}
}
Serial.println("");
Serial.print("My IP address: ");
Serial.println(Ethernet.localIP());
Serial.print("My subnet: ");
Serial.println(Ethernet.subnetMask());
Serial.print("My DNS address: ");
Serial.println(Ethernet.dnsServerIP());
Serial.print("My GateWay address: ");
Serial.println(Ethernet.gatewayIP());
dnClient.begin(Ethernet.dnsServerIP());
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.");
}
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());
Udp.read(packetBuffer, UDP_TX_PACKET_MAX_SIZE);
Serial.println("Contents:");
Serial.println(packetBuffer);
Udp.beginPacket(Udp.remoteIP(), Udp.remotePort());
Udp.write(ReplyBuffer);
Udp.endPacket();
}
digitalWrite(LED_BUILTIN, HIGH); // turn the LED on (HIGH is the voltage level)
delay(10); // wait for a second
digitalWrite(LED_BUILTIN, LOW); // turn the LED off by making the voltage LOW
delay(50); // wait for a second
}
三、测试
3.1、创建UDP终端,连接远程主机IP(开发板IP地址)
3.2、开发板串口输出
开发板输出接收UDP的数据
3.3、抓包软件
抓包接收到的内容
|