Home:ALL Converter>How do I determine whether open socket is TCP or unix domain socket?

How do I determine whether open socket is TCP or unix domain socket?

Ask Time:2014-05-21T08:08:28         Author:Russell Allen

Json Formatter

My code is passed an open socket. This socket could be either a TCP socket (AF_INET) or a Unix Domain Socket (AF_UNIX).

Depending on the domain of the socket, it will need to be handled differently. In particular if the socket is bound to an address then I might want to accept incoming connections in a diffent way.

What is the best way to determine whether the socket I have been passed is a unix domain socket or a TCP socket? The solution would need to work on OS X and Linux at least.

getsockopt appears to allow getting the type of the socket (e.g. SOCK_STREAM etc) but not the domain.

getsockname will return a zero length for unix domain sockets on OSX, but this is officially a bug and the Linux behaviour is different.

Author:Russell Allen,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/23771926/how-do-i-determine-whether-open-socket-is-tcp-or-unix-domain-socket
Joe :

The first member of the struct sockaddr returned by getsockname is sa_family, just test that against the symbolic constants. The bug on OSX lets you assume the unix domain when the returned address structure is zero bytes, for other platforms and domains, just check the returned structure.",
2014-05-21T02:16:27
yy