We present a microscopic index formula for the degeneracy of dyons in four-dimensional N=4 string theory. This counting formula is manifestly symmetric under the duality group, and its asymptotic growth reproduces the macroscopic Bekenstein-Hawking entropy. We give a derivation of this result in terms of the type II five-brane compactified on K3, by assuming that its fluctuations are described by a closed string theory on its world-volume. We find that the degeneracies are given in terms of the denominator of a generalized super Kac-Moody algebra. We also discuss the correspondence of this result with the counting of D-brane states.