2012-02-17 32 views
0

我需要一個可以與IP4和IP6地址一起工作的函數,我需要將地址從它的字符串表示形式(IP4)或十六進制表示形式(IP6)轉換爲它的長整型值。當前的代碼我已經是:如何將IP4和IP6地址轉換爲C中的長整型值?

struct addrinfo *addr; 
// This converts an char* ip_address to an addrinfo, so now I know whether 
// it's a IP4 or IP6 address 
int result = getaddrinfo(ip_address, NULL, NULL, &addr); 
if (result ==0) { 
    struct in_addr dst; 
    result = inet_pton(addr->ai_family, ip_address, &dst); 
    long ip_value = dst->s_addr; 
    freeaddrinfo(addr); 
    return ip_value; 
} 

我也弄了半天,從dst-> s_addr但我敢肯定,這是不正確。任何關於如何解決這個問題的指針都非常感謝!

回答

1

所有dst首先是沒有足夠大的IPv6地址:

unsigned char buf[sizeof(struct in6_addr)]; /* Since it's larger than in_addr */ 
int result = getaddrinfo(ip_address, NULL, NULL, buf); 

如果地址爲IPv4,bufin_addr這是一個uint32_t

uint32_t u; 
memcpy(&u, buf, sizeof(u)); 

如果地址的IPv6轉換爲long實際上並沒有什麼意義。你需要的東西是128位寬或滾動你自己的。最後一點不是那麼容易,所以問問自己:你確定你需要這個嗎?

+0

嗨,非常感謝您的幫助!當你說我的inet_pton調用錯誤時,你的意思是getaddrinfo調用?關於IP6,是的,它應該是128位,我知道我們需要這個,所以我寧願現在修復它....我是否還需要修復inet_pton調用? – DrDee 2012-02-17 23:05:03

+0

@DrDee對不起,我誤解了這個問題。你的'inet_pton'電話實際上幾乎是正確的,我編輯了我的答案。 – cnicutar 2012-02-17 23:06:45

+0

buf中的值始終爲140734799738144(我想這就是sizeof struct in6_addr)。對不起,不斷詢問,但我如何從這裏得到IP地址的'長'表示? – DrDee 2012-02-17 23:32:29

相關問題