secgateway/Product/common/user_hashtable.c

117 lines
2.4 KiB
C

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdint.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include "hlist.h"
#include "user_hashtable.h"
struct hlist_head *hash;
struct hlist_node *p = NULL, *n = NULL ;
int i = 0;
USER_INFO *pNode ;
/*计算hash值 */
struct hlist_head *call_hash(struct hlist_head *hash, uint32_t ip)
{
unsigned int val = ip % 100;
return &hash[val];
}
/*初始化函数 */
int Init_hash()
{
hash = (struct hlist_head*)malloc(sizeof(*hash)*100);
if(NULL == hash)
{
printf("alloc error\n");
return -1;
}
for(i = 0; i < 100; i++)
INIT_HLIST_HEAD(&hash[i]);
}
/*查找用户信息*/
struct user_info *ufind_user(uint32_t user_ip)
{
hlist_for_each_safe(p,n,call_hash(hash,user_ip))
{
pNode = hlist_entry(p, struct user_info ,hnode);
if(pNode != NULL)
printf("user_id :%d\n",pNode->id);
return pNode;
}
}
/*增加用户信息*/
int uadd_user(uint32_t user_ip, int user_id)
{
USER_INFO *pNode =NULL;
hlist_for_each_safe(p,n,call_hash(hash, user_ip)) /*查找ip是否存在hash表中 */
{
pNode = hlist_entry(p, struct user_info ,hnode);
if(pNode != NULL)
printf("IP ALEADY EXISTED\n");
}
if (pNode == NULL)
{
pNode = (struct user_info *)malloc(sizeof(struct user_info));
if (NULL == pNode)
{
return -1;
}
memset(pNode,0,sizeof(struct user_info));
INIT_HLIST_NODE(&pNode->hnode);
pNode->ip = user_ip;
hlist_add_head(&pNode->hnode, call_hash(hash, user_ip));
}
pNode->id = user_id;
}
/*删除用户信息 */
void udelete_user(int user_ip)
{
hlist_for_each_safe(p,n,call_hash(hash,user_ip))
{
pNode = hlist_entry(p, struct user_info ,hnode);
hlist_del(&pNode->hnode);
free(pNode);
}
}
/*删除所有的hash节点 */
void udelete_all()
{
for(i = 0; i < 100; i++)
{
hlist_for_each_safe(p,n,&hash[i])
{
pNode = hlist_entry(p, struct user_info ,hnode);
hlist_del(&pNode->hnode);
free(pNode);
}
}
}
/*打印所有信息信息 */
void uprintf_users()
{
for(i = 0; i < 100; i++)
{
hlist_for_each_safe(p,n,&hash[i])
{
char str[32];
pNode = hlist_entry(p, struct user_info ,hnode);
if(pNode != NULL)
inet_ntop(AF_INET, (void *)&pNode->ip, str, 32);
printf("user_ip :%s user_id:%d\n", str, pNode->id);
}
}
}