我想在 php 的套接字连接中更改每个请求的 IP。(如果我发送大量请求,防止主机阻塞我的 ip)我在下面附上我的代码
function httpGet( $url, $followRedirects=true ) {
global $final_url;
$url_parsed = parse_url($url);
if ( empty($url_parsed['scheme']) ) {
$url_parsed = parse_url('http://'.$url);
}
$final_url = $url_parsed;
$port = $url_parsed["port"];
if ( !$port ) {
$port = 80;
}
$rtn['url']['port'] = $port;
$path = $url_parsed["path"];
if ( empty($path) ) {
$path="/";
}
if ( !empty($url_parsed["query"]) ) {
$path .= "?".$url_parsed["query"];
}
$rtn['url']['path'] = $path;
$host = $url_parsed["host"];
$foundBody = false;
$out = "GET $path HTTP/1.0\r\n";
$out .= "Host: $host\r\n";
$out .= "User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1) Gecko/20061010 Firefox/2.0\r\n";
$out .= "Connection: Close\r\n\r\n";
if ( !$fp = @fsockopen($host, $port, $errno, $errstr, 30) ) {
$rtn['errornumber'] = $errno;
$rtn['errorstring'] = $errstr;
}
fwrite($fp, $out);
while (!@feof($fp)) {
$s = @fgets($fp, 128);
if ( $s == "\r\n" ) {
$foundBody = true;
continue;
}
if ( $foundBody ) {
$body .= $s;
} else {
if ( ($followRedirects) && (stristr($s, "location:") != false) ) {
$redirect = preg_replace("/location:/i", "", $s);
return httpGet( trim($redirect) );
}
$header .= $s;
}
}
fclose($fp);
return(trim($body));
}
最佳答案
您无法更改(欺骗)您发送的 IP 地址。但是,您可以使用像 SOCKS4/5 这样的代理。或带有 PHP 扩展名的 HTTP 代理 cURL .这将导致预期的效果。
但是,请注意,您应该首先收集更多关于 proxy 的知识。在尝试随机的东西之前工作(尤其是像你粘贴的代码,这不再是你想用 PHP5 做的任何事情)。
关于php 更改套接字中请求的 ip,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3080881/