Add checks for invalid socket when creating sockets.
Fixes #1005