Chinaunix首页 | 论坛 | 博客
  • 博客访问: 516346
  • 博文数量: 118
  • 博客积分: 10028
  • 博客等级: 上将
  • 技术积分: 1820
  • 用 户 组: 普通用户
  • 注册时间: 2007-11-07 18:46
文章分类

全部博文(118)

文章存档

2009年(12)

2008年(106)

我的朋友

分类: C/C++

2008-11-12 23:00:50



用MAC作为KEY,来插入、查找MAC对应的IP...HASH桶深131


代码

#include <stdio.h>
#include <stdlib.h>

struct mac_ip{
    char Mac[18];
    char Ip[16];
    struct mac_ip *next;
};
typedef struct mac_ip Mac_IP;


int hahash(const char mac[],int n)
{
    int len=strlen(mac);
    int i,sum=0;

    for(i=0;i<len;i++)
        sum+=mac[i];

    return(sum%n);
}


void insert_new(Mac_IP *tank[],char mac[],char ip[])
{
    Mac_IP *temp;
    int i,n;

    temp=(Mac_IP*)malloc(sizeof(Mac_IP));
    if(temp == NULL){
        printf("Malloc error!\n");
        exit(1);
    }

    strcpy(temp->Mac,mac);
    strcpy(temp->Ip,ip);
    temp->next=NULL;

    n=hahash(mac,131);
    if(tank[n] == NULL){
        tank[n]=temp;
    }
    else{
        temp->next=tank[n];
        tank[n]=temp;
    }
}

char *hash_search(Mac_IP *tank[],char mac[])
{
    int n;
    Mac_IP *p;

    n=hahash(mac,131);

    if(tank[n] == NULL){
        printf("No record of this MAC!\n");
        return NULL;
    }
    else{
        p=tank[n];
        while(p != NULL){
            if(strcmp(p->Mac,mac) == 0)
               return(p->Ip);
            else
                p=p->next;
        }

        printf("No record of this MAC!\n");
        return NULL;

    }
}

int main(int argc,char **argv)
{
    Mac_IP *tank[131];
    int i;
    char *ip=NULL;

    for(i=0;i<131;i++)
        tank[i]=NULL;

    insert_new(tank,"10-2F-34-25-6D-DE","192.168.10.25");
    insert_new(tank,"10-2F-34-6D-DE-25","192.168.1.126");
    insert_new(tank,"4D-25-E4-2C-62-DE","10.0.0.234");

    ip=hash_search(tank,"10-2F-34-25-6D-DE");
    if(ip != NULL){
        printf("ip:%s\n",ip);
    }

    return 0;
}

阅读(2815) | 评论(0) | 转发(0) |
0

上一篇:连表逆序

下一篇:几个笔试

给主人留下些什么吧!~~