2014-04-22 48 views
0

我正在实施一个聊天室应用程序,使用C语言的原始套接字用于我的大学项目。我在分配IP地址时遇到了问题。在IP头中分配IP地址C

数据包从套接字接收。我正在解析它,如图所示。现在如何分配IP地址。

我宁愿按照所示的方式(如果可能,使用rcv_ip作为字符)来完成它。所以在给出使用struct in_addr的建议之前,请帮助我解决这个问题。因为我尝试过其他方法,这些方法正在进一步给我造成困惑。

main() 
{ 
char *rcv_ip; 
char *packet; 
int len; 
struct iphdr ip_header; 
rcv_ip=ParseIPHeader(packet,len); 
printf("\n %s ",rcv_ip); //printing some junk 
printf("\n %s ",inet_addr(rcv_ip)); //giving seg fault 
printf("\n %s",inet_ntoa(*((struct in_addr*)ip_header->daddr))); //printing correct ip 

ip_header CreateIPHeader(rcv_ip+5,rcv_ip); 
} 

现在是ParseIPHeader函数。

char *ParseIPHeader(packet,len) 
{ 
    struct iphdr *ip_header; 
    struct ethhdr *eth_header; 
    char *ret_ip; 

    ip_header=(struct iphdr *)(packet+sizeof(struct ethhdr)); 
    ret_ip=malloc(10); 
    memset(ret_ip,0,10); 
    memcpy(ret_ip,&(ip_header->daddr),sizeof(ip_header->daddr)); 
    memcpy(ret_ip+5,&(ip_header->saddr),4); 

    return ret_ip; 
} 

struct iphdr *CreateIPHeader(char *src_ip,char *dst_ip) 
{ 
    struct iphdr *ip_header; 
ip_header=malloc(sizeof(struct iphdr)); 
    //main part. How to do this?? 
    ip_header->saddr = inet_addr(src_ip); //please correct it. 
ip_header->daddr = inet_addr(dst_ip); 


return(ip_header); 
} 

谢谢:)

回答

0

你似乎期望IP地址字符串,因为你尝试打印一个与printf()%s格式说明。这是不正确的; IP地址在标头中是二进制的。

这意味着IPv4地址只使用32位,而文本表示可能最多使用3 + 1 + 3 + 1 + 3 + 1 + 3 = 15个字符(加终止符,所以为16)。

阅读更多IP基础知识。

+0

是的..谢谢。这意味着我必须使用一些包含ipaddress的结构体。会**结构in_addr **没问题?我想我需要这个结构的两个对象,然后分配源IP和目标IP。但我将如何从** CreateIPHeader **函数返回两个IP? – user3542109