diff --git a/server/metadata.go b/server/metadata.go index 605ec1f7..0b1b1654 100644 --- a/server/metadata.go +++ b/server/metadata.go @@ -209,7 +209,7 @@ func (m *metadataAPI) brokerCache(serverIDs map[string]struct{}) ([]*client.Brok // argument is the expected number of peers to get a response from. func (m *metadataAPI) fetchBrokerInfo(ctx context.Context, numPeers int) ([]*client.Broker, *status.Status) { // Add ourselves. - connectionAddress := m.config.GetConnectionAddress() + connectionAddress := m.getConnectionAddress() brokers := []*client.Broker{{ Id: m.config.Clustering.ServerID, Host: connectionAddress.Host, diff --git a/server/server.go b/server/server.go index b66993a4..71cee0ba 100644 --- a/server/server.go +++ b/server/server.go @@ -264,12 +264,23 @@ func (s *Server) IsRunning() bool { func (s *Server) GetListenPort() int { s.mu.RLock() defer s.mu.RUnlock() + return s.port +} + +// getConnectionAddress returns the connection address that should be used by +// the server. It uses the port the server is currently listening to if the +// connection port is 0, so that an OS-assigned port can be used as a connection +// port. +func (s *Server) getConnectionAddress() HostPort { + s.mu.RLock() + defer s.mu.RUnlock() - if s.listener == nil { - return 0 + address := s.config.GetConnectionAddress() + if address.Port == 0 { + address.Port = s.port } - return s.listener.Addr().(*net.TCPAddr).Port + return address } // recoverAndPersistState recovers any existing server metadata state from disk @@ -819,7 +830,7 @@ func (s *Server) handleServerInfoRequest(m *nats.Msg) { return } - connectionAddress := s.config.GetConnectionAddress() + connectionAddress := s.getConnectionAddress() data, err := proto.MarshalServerInfoResponse(&proto.ServerInfoResponse{ Id: s.config.Clustering.ServerID, Host: connectionAddress.Host,