SSH X11 forwarding fails

Problem

X forwarding does not work with ssh -X or ssh -Y. When starting a program, it says:

E233: cannot open display
Error: Can't open display: 

SSH does not indicate that X11 forwarding failed, but it gives these messages in debug mode:

debug1: Requesting X11 forwarding with authentication spoofing.
debug2: channel 0: request x11-req confirm 0

Debugging

Try starting sshd on a different port under debug mode.

/usr/sbin/sshd -d -D -p 2222

This enables debug mode, sshd does not detach and run as daemon and sshd listens on port 2222. This allows you to debug the problem while leaving the normal sshd server running. In my case it gave this:

Failed to allocate internet-domain X11 display socket.
debug1: x11_create_display_inet failed.

Solution

Check that localhost is reachable. In my case, the lo loopback interface was not enabled, and my /etc/hosts file was empty. After enabling the loopback interface and adding 127.0.0.1 localhost to my hosts file, X11 forwarding worked again.