I found the command
sfdx force:package:installed:list -u
here in this post Query for Package Ids installed on an org?
It's a line from SFDCfox's answer. I'm interested in the results that he got because I needed the IDs for the installed packages. However, can I have those command in my apex class?