2010-05-05 99 views
1
#define IPTOSBUFFERS 12 
char *iptos(u_long in) 
{ 
    static char output[IPTOSBUFFERS][3*4+3+1]; 
    static short which; 
    u_char *p; 

    p = (u_char *)∈ 
    which = (which + 1 == IPTOSBUFFERS ? 0 : which + 1); 
    _snprintf_s(output[which], sizeof(output[which]), sizeof(output[which]),"%d.%d.%d.%d", p[0], p[1], p[2], p[3]); 
    return output[which]; 
} 

有什么我很想理解它吗?你能解释一下这个ip_to_string函数是如何工作的吗?

+1

你不了解什么?它看起来像是一个无符号的long,并且不幸的是它返回一个带有悬挂指针的ip字符串表示。 – WhirlWind 2010-05-05 15:51:57

+0

'172.16.48.1'的u_long是什么? – user198729 2010-05-05 15:53:53

+1

172 * 256^3 + 16 * 256^2 + 48 * 256^1 + 1 – WhirlWind 2010-05-05 15:56:11

回答

1

这是一个答案,基于似乎令人困惑的评论。

IP地址通常在内部表示为32位。它通常表示为4个十进制字段,范围从0到255.要从十进制表示转换为32位表示,简单地将字段从十进制转换为二进制(或十六进制),从左到右,并将它们连接起来。

因此,1.2.3.4变为字段0x01,0x02,0x03和0x04。因此,它们的32位(无符号长整型)表示是:0x01020304。当然,这也受字节顺序的限制...

要将32位地址作为字符串打印,只需查看构成它的四组8位数据中的每一组,然后将它们打印为十进制有点之间的整数。

2

附加说明下面为您的享受:

// This is the number of IP string buffers. 
#define IPTOSBUFFERS 12 

char *iptos(u_long in) 
{ 
    // 12 buffers, each big enough to hold maximum-sized IP address 
    // and nul terminator. 
    static char output[IPTOSBUFFERS][3*4+3+1]; 

    // Last buffer used. 
    static short which; 

    // Get uns. char pointer to IP address. 
    u_char *p; 
    p = (u_char *)∈ 

    // Move to next string buffer, wrapping if necessary. 
    which = (which + 1 == IPTOSBUFFERS ? 0 : which + 1); 

    // Output IP address by accessing individual unsigned chars in it. 
    _snprintf_s(output[which], sizeof(output[which]), sizeof(output[which]), 
     "%d.%d.%d.%d", p[0], p[1], p[2], p[3]); 

    // Return the current buffer. 
    return output[which]; 
} 

它的工作原理是因为IPv4地址的表示是在存储器中的32位的值,并且每个所述四个区段的占据每一个八位字节。因此,将32位整数的地址转换为四字符数组然后使用该数组提取单个段是相对简单的事情。当然,这是根据具有特定位宽度的数据类型来预测的,因此它不是便携式的。

奇怪的是12-IP地址循环队列。也许这样可以一次获得多达12个IP地址,而不会覆盖字符串,尽管我认为我从未遇到过超过两个(可能是三个代理服务器或pass-thru服务器)的情况需要在同一时间。我不认为这是线程安全的,因为在线程环境中对which的修改本质上是危险的。

相关问题