📄 udp.c
字号:
#include "ethernet.h"
#include "ip.h"
#include "udp.h"
#include "ring.h"
#include "arp.h"
extern Net_inf_struc net_inf;
xdata Uint8 tx_buf[1500];
ring_struc ring;
Uint8 rx_buf[MAX_DUP_BUFFER_LENGTH*MAX_DUP_BUFFER_COUNT];
Bool udp_open(Uint8 *pip,Uint16 port_local,Uint16 port_remote)
{
if(net_inf.portnumber_local)
return FALSE;
net_inf.portnumber_local = port_local;
net_inf.portnumber_remote = port_remote;
if(pip==NULL)
memset(net_inf.ip_remote,0,INADDR_LEN);
else
memcpy(net_inf.ip_remote,pip,INADDR_LEN);
ring_init(&ring,rx_buf,MAX_DUP_BUFFER_LENGTH,MAX_DUP_BUFFER_COUNT);
}
void udp_close()
{
net_inf.portnumber_local = 0;
net_inf.portnumber_remote = 0;
}
Bool udp_sendto(Uint8 *pip,Uint16 remote_port,Uint8 *pbuf,Uint16 length)
{
xdata Ip_struc* ipPkt;
xdata Udphdr_struc* udpPkt;
ipPkt = ( Ip_struc*) (tx_buf + sizeof(Ether_header_struc));
udpPkt = ( Udphdr_struc*) ((Uint8*) ipPkt + sizeof(Ip_struc));
// UDP header
udpPkt->source = net_inf.portnumber_local ;
udpPkt->dest = remote_port;
udpPkt->len = length+sizeof(Udphdr_struc);
udpPkt->check = 0;
//content
memcpy((Uint16 *)udpPkt+ sizeof(Udphdr_struc),pbuf,length);
// destination IP
memcpy(&ipPkt->ip_dst, pip, INADDR_LEN);
// fill source address for checksum - use a zero ip address if we do not have one (eg sending bootp)
memcpy(&ipPkt->ip_src, net_inf.ip_local, INADDR_LEN);
// packet length, protocol & id are the same
ipPkt->ip_len = udpPkt->len + sizeof(Ip_struc);
ipPkt->ip_p = IPPROTO_UDP;
ipPkt->ip_id = 0;
ipPkt->ip_ttl = 64;
// insert checksum & send
//udpPkt->check = cpu_checksum(( Uint16 *) ipPkt, (aLength | CPU_CHECKSUM_INC_IP) - sizeof(Ip_struc));
return ip_send(tx_buf);
}
Bool udp_send(Uint8 *pbuf,Uint16 length)
{
return udp_sendto(net_inf.ip_remote,net_inf.portnumber_remote,pbuf,length);
}
Uint16 udp_recv(Uint8 *pbuf,Uint16 length)
{
Uint16 i;
if(ring_read(&ring,tx_buf)){
i = tx_buf[0]<<8;
i |= tx_buf[1];
length = Min(length,i);
memcpy(pbuf,tx_buf+2,length);
return length;
}
return 0;
}
void udp_process(Uint8* pudp)
{
xdata Udphdr_struc* udpPkt;
udpPkt = (Udphdr_struc*)pudp;
if(udpPkt->dest != net_inf.portnumber_local)
return;
if(net_inf.portnumber_remote == 0)
net_inf.portnumber_remote = udpPkt->source;
if(udpPkt->source != net_inf.portnumber_remote)
return;
udpPkt->check = udpPkt->len-sizeof(Udphdr_struc);
ring_write(&ring,pudp+sizeof(Udphdr_struc)-2);
}
void tick()
{
xdata Uint8 buffer[1500];
Uint16 i;
if(ethernet_receive(buffer)){
i = buffer[12]<<8;
i |= buffer[13];
switch(i){
case ETHERTYPE_IP:
ip_receive(buffer);
break;
case ETHERTYPE_ARP:
arp_receive(buffer);
break;
}
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -