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

南楼画角 提交于 2019-12-05 20:55:18

I think its not possible using fsockopen. But its possible in curl, fopen and stream functions. What you need is stream_socket_client() function.

Here are some ways to achieve it.

  1. Using context parameters which can be used in fopen function family and stream function family. See the example.

    $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);
    

    Also stream_socket_client

    $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. Using socket_bind. PHP.NET got a simple example here.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!