How to programatically find default ssh key?

From the man page for ssh:

     -i identity_file
         Selects a file from which the identity (private key) for public
         key authentication is read.  The default is ~/.ssh/identity for
         protocol version 1, and ~/.ssh/id_dsa, ~/.ssh/id_ecdsa and
         ~/.ssh/id_rsa for protocol version 2.  Identity files may also be
         specified on a per-host basis in the configuration file.  It is
         possible to have multiple -i options (and multiple identities
         specified in configuration files).  ssh will also try to load
         certificate information from the filename obtained by appending
         -cert.pub to identity filenames.

Subsequently, if it is in a location that can be found automatically by ssh, the path won't need to be specified at all. i.e.

ssh -i ~/.ssh/id_rsa [email protected]

and

ssh [email protected]

will both work in the same way. If you need to find the key location programatically for a reason other than using ssh (i.e. populating authorized keys) you can check all the locations that the config file checks, and parse the ssh_config file to look for indiviual host entries. From man ssh_config:

         The file name may use the tilde syntax to refer to a user’s home
         directory or one of the following escape characters: ‘%d’ (local
         user’s home directory), ‘%u’ (local user name), ‘%l’ (local host
         name), ‘%h’ (remote host name) or ‘%r’ (remote user name).

So you would also have to parse this format to locate individual files (if defined).