我正在尝试创建一个哈希表来存储简单数据(但很多),找到了库uthash,我正在尝试实现它;但是,我得到一个段。每当我尝试添加或读取数据时都会出现错误。有什么建议?
从简单的使用习惯我看到struct my_struct *s;
代码:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <inttypes.h>
#include <linux/ip.h>
#include <linux/tcp.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include "uthash.h"
unsigned char full_packet[] = {
0x45, 0x00, 0x00, 0x40, 0x63, 0x7b, 0x40, 0x00, 0x39, 0x06, 0x37, 0x2f, 0x17, 0xee, 0x82, 0xaa,
0xac, 0x6b, 0x60, 0x0a, 0xcc, 0x45, 0x01, 0xc4, 0xd3, 0x60, 0xa1, 0x2e, 0x00, 0x00, 0x00, 0x00,
0xb0, 0x02, 0xff, 0xff, 0x9b, 0xd1, 0x00, 0x00, 0x02, 0x04, 0x05, 0x46, 0x01, 0x03, 0x03, 0x05,
0x01, 0x01, 0x08, 0x0a, 0x6a, 0x47, 0x47, 0xab, 0x00, 0x00, 0x00, 0x00, 0x04, 0x02, 0x00, 0x00,
};
struct my_struct {
char id; /* key */
char name;
UT_hash_handle hh; /* makes this structure hashable */
};
struct my_struct *SYNs = NULL;
void add_user(char user_id, char *name) {
struct my_struct *s;
printf("UserID: %s and name %s=\n", user_id, name);
HASH_FIND_INT(SYNs, &user_id, s); /* id already in the hash? */
if (s==NULL) {
s = (struct my_struct*)malloc(sizeof(struct my_struct));
s->id = user_id;
HASH_ADD_INT( SYNs, id, s ); /* id: name of key field */
}
strcpy(s->name, name);
}
int main(int argc, char *argv[]) {
struct iphdr *ip;
struct in_addr ipa;
char src_ip_str[20];
char dst_ip_str[20];
// Get IP addresses in char form
ip = (struct iphdr *) full_packet;
ipa.s_addr=ip->saddr;
strcpy (src_ip_str, inet_ntoa(ipa));
ipa.s_addr=ip->daddr;
strcpy (dst_ip_str, inet_ntoa(ipa));
struct iphdr *iph = ((struct iphdr *) full_packet);
fprintf(stdout, "IP{v=%u; ihl=%u; tos=%u; tot_len=%u; id=%u; ttl=%u; protocol=%u\n"
,iph->version, iph->ihl*4, iph->tos, ntohs(iph->tot_len), ntohs(iph->id), iph->ttl, iph->protocol);
if (iph->protocol == 6){
struct tcphdr *tcp = ((struct tcphdr *) (full_packet + (iph->ihl << 2)));
fprintf(stdout, "TCP{sport=%u; dport=%u; seq=%u; ack_seq=%u; flags=u%ua%up%ur%us%uf%u; window=%u; urg=%u}\n",
ntohs(tcp->source), ntohs(tcp->dest), ntohl(tcp->seq), ntohl(tcp->ack_seq)
,tcp->urg, tcp->ack, tcp->psh, tcp->rst, tcp->syn, tcp->fin, ntohs(tcp->window), tcp->urg_ptr);
add_user(src_ip_str, dst_ip_str);
printf("Data added!\n");
}
}
uthash.h is found here
答案 0 :(得分:1)
代码中的某些内容需要注意:
struct my_struct {
char id; /* key */
char name; // <----HERE!
UT_hash_handle hh; /* makes this structure hashable */
};
您可能需要char *name
或char name[WHATEVER_SIZE]
,因为在您的add_user()
中,您尝试在此处复制字符串。如果您选择使用指针,请不要忘记分配。