Skip to content

Zend_Mail_Protocol_Smtp must use context to bind specific IP. #43

Open
zfbot opened this Issue Apr 5, 2013 · 1 comment

1 participant

@zfbot
zfbot commented Apr 5, 2013

Jira Information

Original Issue: ZF-12489
Issue Type: Improvement
Reporter: Federico Gon
Created: 12/20/12
Assignee: Dolf Schimmel (Freeaqingme)
Components: Zend_Mail

Description

If you have a more than 1 IP in your server, you can't really know which IP Zend_Mail_Protocol_Smtp will use.

Solution: Use stream_context_set_params to set "bindto" param

application.ini:

resources.mail.transport.bindto    = "xxx.xxx.xxx.xxx" ; Setting the IP or the port to 0 will let the system choose the IP and/or port. (http://php.net/manual/en/context.socket.php)

Code:
class: Zend_Mail_Protocol_Smtp


// new property
protected $_bindto = null;

    public function __construct($host = '127.0.0.1', $port = null, array $config = array())
    {
        ...

        if(isset($config['bindto']) && !empty($config['bindto']))
        {
            $this->_bindto = $config['bindto'];
        }
        else
        {
            $this->_bindto = gethostbyname(gethostname());
        }

        parent::__construct($host, $port);
    }


    protected function _connect($remote)
    {
        $errorNum = 0;
        $errorStr = '';

        // open connection

/* Here use de new property to build a context */
        $context = null;
        if(!is_null($this->_bindto))
        {
            $opts = array('socket' => array('bindto' => $this->_bindto));
            $context = stream_context_create($opts);
        }

        $this->_socket = @stream_socket_client($remote, $errorNum, $errorStr, self::TIMEOUT_CONNECTION, STREAM_CLIENT_CONNECT, $context);

        if ($this->_socket === false) {
            if ($errorNum == 0) {
                $errorStr = 'Could not open socket';
            }
            /**
             * @see Zend_Mail_Protocol_Exception
             */
            require_once 'Zend/Mail/Protocol/Exception.php';
            throw new Zend_Mail_Protocol_Exception($errorStr);
        }

        if (($result = $this->_setStreamTimeout(self::TIMEOUT_CONNECTION)) === false) {
            /**
             * @see Zend_Mail_Protocol_Exception
             */
            require_once 'Zend/Mail/Protocol/Exception.php';
            throw new Zend_Mail_Protocol_Exception('Could not set stream timeout');
        }

        return $result;
    }

@zfbot
zfbot commented Apr 5, 2013

This issue was ported from the ZF2 Jira Issue Tracker at
http://framework.zend.com/issues/browse/ZF-12489

Known GitHub users mentioned in the original message or comment:

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Something went wrong with that request. Please try again.