哪位朋友能帮忙研究下这段程序哪里有问题?

来源:百度知道 编辑:UC知道 时间:2024/05/13 15:04:59
做的是个模拟路由表工作的简单程序,将键盘输入的目的ip地址和表中掩码按位与运算后再同表中的目的ip做比较,如果相同则从相应的端口转发出去.程序不报错,但是却得不到预期效果,不知道问题在哪里,有朋友能帮忙看看,调试下吗
#include <stdio.h>
#include <string.h>
main()
{
struct table
{
unsigned long Dest;
unsigned long Mask;
unsigned long Gate;
unsigned long Inte;
};
struct table tab[4]={
{0xcb4acd00,0xffffffff,0xcb4acd01,0xcb4acd01},
{0xcb4ace00,0xffffffff,0xcb4ace01,0xcb4ace01},
{0xcb4acf00,0xffffffff,0xcb4acf01,0xcb4acf01},
{0xcb4ad000,0xffffffff,0xcb4ace02,0xcb4ace01}};
unsigned long i1,i2,i3,i4;
unsigned long ip;
int i;
int m;
char ip_str[33]={0};

printf("Please input destination ip address:");
scanf("%s",ip_str);
sscanf(ip_str,"%d.%d.%d.%d",&i1,&i2,&i3,&i4);
ip=(i1<<24)+(i2<<16)+(i3<<8)+i4;
for(m=0;m<=3;m++)
if(ip&tab[m].Mask==tab[m].Dest)
printf("IP data

程序是存在一个细小的错:运算符优先级的问题.
下面是修改后的程序,能正确运行了。
下面给出两组测试数:
IP1:203.74.205.0
IP2:203.74.208.0
运行结果分别:
port1:203.74.205.1
port2:203.74.206.1

#include <stdio.h>
#include <string.h>
main()
{
int flag=0;/*加个标志*/
struct table
{
unsigned long Dest;
unsigned long Mask;
unsigned long Gate;
unsigned long Inte;
};
struct table tab[4]={
{0xcb4acd00,0xffffffff,0xcb4acd01,0xcb4acd01},
{0xcb4ace00,0xffffffff,0xcb4ace01,0xcb4ace01},
{0xcb4acf00,0xffffffff,0xcb4acf01,0xcb4acf01},
{0xcb4ad000,0xffffffff,0xcb4ace02,0xcb4ace01}
};
unsigned long i1,i2,i3,i4;
unsigned long ip;
/*int i; i在程序中没有用到,最好去掉*/
int m;
char ip_str[33]={0};

printf("Please input destination ip address:");
scanf("%s",ip_str);

sscanf(ip_str,"%d.%d.%d.%d",&i1,&i2,&i3,&i4);
ip=(i1