📄 ip.c
字号:
#include "ethernet.h"
#include "arp.h"
#include "ip.h"
#include "icmp.h"
#include "udp.h"
extern Net_inf_struc net_inf;
void ip_config(Uint8 *pip_local, Uint8 *pip_remote,Uint8 *pip_gateway,Uint8 *pip_mask)
{
if(pip_local==NULL)
memset(net_inf.ip_local,0,INADDR_LEN);
else
memcpy(net_inf.ip_local,pip_local,INADDR_LEN);
if(pip_remote==NULL)
memset(net_inf.ip_remote,0,INADDR_LEN);
else
memcpy(net_inf.ip_remote,pip_remote,INADDR_LEN);
if(pip_gateway==NULL)
memset(net_inf.ip_gateway,0,INADDR_LEN);
else
memcpy(net_inf.ip_gateway,pip_gateway,INADDR_LEN);
if(pip_mask==NULL)
memset(net_inf.ip_mask,0,INADDR_LEN);
else
memcpy(net_inf.ip_mask,pip_mask,INADDR_LEN);
}
Uint16 cpu_checksum( Uint16* pBuffer, Uint16 aLength)
{
Uint32 checksum=0;
Uint16 i;
for(i=0;i<aLength;i++)
checksum+=(Uint32)(*pBuffer++);
checksum=(checksum>>16)+(checksum&0xffff);
checksum=(checksum>>16)+(checksum&0xffff);
return (Uint16)(~checksum);
}
//-----------------------------------------------------------------
Bool ip_send(Uint8 *pBuffer)
{
Ether_header_struc* ethHdr;
Ip_struc* ipPkt;
Uint8 *pmac;
ethHdr = ( Ether_header_struc*)pBuffer;
ipPkt = ( Ip_struc*) (pBuffer + sizeof(Ether_header_struc));
ipPkt->ip_sum =0;
ipPkt->ip_sum = cpu_checksum(( Uint16 *) ipPkt, 10);
pmac= get_macaddr(ipPkt->ip_dst);
if(pmac==NULL){
//can't find
arp_send(ARPOP_REQUEST, 0, ipPkt->ip_dst);
memset(ethHdr->ether_dhost, 0xff, ETHER_ADDR_LEN);
}
else{
memcpy(ethHdr->ether_dhost,pmac, ETHER_ADDR_LEN);
}
// MAC
ethHdr->ether_type = ETHERTYPE_IP;
memcpy(ethHdr->ether_shost,net_inf.mac,ETHER_ADDR_LEN);
return ethernet_send(pBuffer, ipPkt->ip_len + sizeof(Ether_header_struc));
}
//-----------------------------------------------------------------
// IP packet receive & action
Bool ip_receive(Uint8* pBuffer)
{
Ip_struc* ipPkt;
Uint8 i;
ipPkt = ( Ip_struc*) (pBuffer + sizeof( Ether_header_struc));
if(ipPkt->ip_hl_v != IPVERSION_HEADERLEN)
return FALSE;
i = memcmp(net_inf.ip_local,ipPkt->ip_dst, INADDR_LEN);
if(i){//not for this ip, check boardcast addr
for(i=0;i<INADDR_LEN;i++){
if(ipPkt->ip_dst[i] != net_inf.ip_local[i]){
if(ipPkt->ip_dst[i] != 0xff)
return FALSE;
}
}
}
if (cpu_checksum(( Uint16 *) ipPkt, 10) == 0){
switch(ipPkt->ip_p){
case IPPROTO_ICMP:{
icmp_receive(pBuffer);
break;
}
case IPPROTO_UDP:{
udp_process((Uint8*)ipPkt + sizeof(Ip_struc));
break;
}
case IPPROTO_TCP:{
// tcp_receive(ipPkt->ip_len - sizeof(Ip_struc));
break;
}
default:
return FALSE;
}
}
return TRUE;
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -