2012-03-20 137 views
1

我試圖將網址映射到範圍[0,50]中用於移植的數字,它應該在範圍內均勻分佈,這樣就不會損壞端口。將網址映射到隨機端口範圍

下面是我的代碼,但我可以找出爲什麼模數不適合我。

$fetch_url = "http://74.125.224.72/profile/user"; 
    $hash = sha1($fetch_url); 
    $hasher = substr($hash,1,50); 
    $port_index = hexdec($hasher)%50; 
    $port = 8700 + $port_index; 

似乎一切工作到$ port_index返回0.請記住,「用戶」是每次都不同的實際用戶名。

的最終目標是下面寫:

http://74.125.224.72/profile/j - port = 8701 
    http://74.125.224.72/profile/m - port = 8702 
    http://74.125.224.72/profile/p - port = 8703 

而且應該是每次這種方式在用戶登錄並點擊他們的個人資料。

任何想法?

感謝 -J

回答

1

我相信這個問題是一個SHA1哈希的hexdec轉換是如此巨大,PHP還挺停止處理它作爲一個數字。你應該修剪散列和十六進制的最後幾個字符。看起來你可能一直在用你的substr,但是sha1是40個字符,你做了50個substr。那50是一個錯誤嗎?

正因爲如此,hexdec返回類似於'5.4627305075531E + 46'的東西,它不會正確地穿過模量。試試:

$fetch_url = "http://74.125.224.72/profile/user"; 
$hash = sha1($fetch_url); 
$hasher = substr($hash,-5); // get last 5 
$port_index = hexdec($hasher)%50; 
$port = 8700 + $port_index; 
+0

這樣做。謝謝kingcoyote。 – JMP 2012-03-21 00:12:40