[SOLVED] Datagram Socket - get local port


#1

Hello!

I use the datagram socket to connect to other software. In the constructor, I pass “0” for the local port, so the operating System can choose a port itself. How can i find out, which port has been chosen? getPort() seems to return the remotePort.

StrangeMan


#2

I don’t think there’s any way of getting that; if you need to know the port, I think you’d have to supply a number yourself.


#3

i previously worked with oscpack. oscpack brings its own udp classes, and there it was possible (at least under windows) to let the OS choose a port and later on get that port.
Now that I port my stuff to work on OSX, too, I’m trying to get that running with the Datagram socket.

I chose, to manually try to find a free port and never pass a “0” to the DatagramSocket. So for everybody who needs to bind to the first free local port, here is my solution:[code]
int m_local_port = … ;
DatagramSocket* m_udp_socket = … ;
bool m_is_bound = false;

    // Port = auto assign?
    if (m_local_port == 0)
    {
        // lowest, undefined port
        m_local_port = 49152;
        // try to bind to a port, until a free port is found
        while ((m_local_port<65535) && (!m_is_bound))
        {
            m_local_port++;
            m_is_bound = m_udp_socket->bindToPort(m_local_port);
        }
    }
    // no auto-assign -> bind to port right away
    else
    {
        m_is_bound = m_udp_socket->bindToPort(m_local_port);
    }[/code]

Hopefully someone else might find this helpful.