我可以从一个特定的IP(如果机器有两个IP)打开PHP中的套接字吗


Can I open socket in PHP from a specific IP (if the machine has two IPs)?

我使用PHPMailer,它使用fsockopen访问SMTP服务器。

但该机器有两个IP,它们具有不同的反向DNS记录。因此,在电子邮件标题中,我得到了以下内容:

Received: from one-server.tld (HELO another-server.tld) ...

我需要隐藏one-server.tld以支持another-server.tld。但我需要两个IP的当前RDNS设置。

我认为使用fsockopen是不可能的。但在curlfopenstream的功能中是可能的。您需要的是stream_socket_client()函数。

以下是一些实现它的方法。

  1. 使用可以在fopen函数族和stream函数族中使用的上下文参数。请参见示例。

    $opts = array(
        'socket' => array(
            'bindto' => '192.168.0.100:0',
        ),
    );
    // create the context...
    $context = stream_context_create($opts);
    $contents = fopen('http://www.example.com', 'r', false, $context);
    

    还流式传输_套接字客户端

    $fp = stream_socket_client("tcp://www.example.com:80", $errno, $errstr, 30, STREAM_CLIENT_CONNECT, $opts);
    if (!$fp) {
        echo "$errstr ($errno)<br />'n";
    } else {
        fwrite($fp, "GET / HTTP/1.0'r'nHost: www.example.com'r'nAccept: */*'r'n'r'n");
        while (!feof($fp)) {
            echo fgets($fp, 1024);
        }
        fclose($fp);
    }
    
  2. 使用socket_bind。PHP.NET在这里得到了一个简单的例子。