用C写的rip协议
这是其中的广播request程序片段:
void RouteInit()
{
int i,optval=0,length,error;
routeNum = 0;
// init local socket address and ip address
GetLocalIP();
// init route table items
for(i = 0; i < MAX_NUM; i++)
{
SetRouteEntry(&routeTable[i].routeInfo,"0.0.0.0",0,0);
routeTable[i].isvalid = 0;
routeTable[i].timer = 0;
routeTable[i].statue = 0;
inet_aton("0,0,0,0",&routeTable[i].sourceIPAddr);
}
// init request packet
SetRoutePacket(&reqPacket,REQUEST);
SetRouteEntry(&reqPacket.routeEntry[0],"0.0.0.0",0,16);
// init response packet
SetRoutePacket(&resPacket,RESPONSE);
recvSockAddr.sin_family = AF_INET;
recvSockAddr.sin_port = htons(PORT);
recvSockAddr.sin_addr.s_addr = htonl(INADDR_ANY);
sendSockAddr.sin_family = AF_INET;
sendSockAddr.sin_port = htons(PORT);
// inet_aton("240.255.255.255",&sendSockAddr.sin_addr);
sendSockAddr.sin_addr.s_addr = htonl(INADDR_ANY);
EntryInit();
sock = socket(AF_INET,SOCK_DGRAM,0);
if(sock<0)
{
printf("cannot create a socket!\n");
exit(1);
}
if(setsockopt(sock,SOL_SOCKET,SO_BROADCAST,&optval,sizeof(int)) != 0)
{
printf("cannot broadcast!\n");
close(sock);
exit(1);
}
if(bind(sock,(struct sockaddr*)&recvSockAddr,sizeof(recvSockAddr))<0)
{
printf("cannot bind to port\n");
close(sock);
exit(1);
}
length=sizeof recvSockAddr;
getsockname(sock,(struct sockaddr*)&recvSockAddr,&length);
printf("Port %d is opened. Listen for packet...\n",ntohs(recvSockAddr.sin_port));
FD_ZERO(&fdSet);
FD_SET(sock,&fdSet);
error = sendto(sock,&reqPacket,4+sizeof(struct ROUTE_ENTRY),0,(struct sockaddr*)(&sendSockAddr),sizeof(struct sockaddr));
if(
2021-05-29 13:29:24
15KB
rip
c语言
1