Using getpeername with descriptor as 0

I have old code with this line:

getpeername(0, (struct sockaddr *)&sin, &namelen)

      

What does it do getpeername(0,...)

? Does it work across the OS? I tried to compile and run in SUN and I get this => Socket to non-socket operation I did some research on the internet but I didn't understand why I am using this line, it returns my "localhost"?

thank

+3


source to share


3 answers


It looks for a peer-to-peer network, that is, a host on the other side of the network, for file descriptor 0, which is STDIN.



This is probably an easy way to check if standard input has been redirected to a socket. which is usually used in daemons like inetd: if it returns an error, then it was started as a normal daemon, but if it succeeds, then it starts as an inetd daemon, and this very socket is the one that will be used for the daemon's operation.

+3


source


Try it man getpeername

. This is a POSIX API, so it must be supported on UNIX and Linux platforms.

The first argument must be fd of the connected socket. He will fill in the partner's address (on the other side). Details on how to use the length argument: see the man page

Your call will only work if fd 0 (stdin) is bound to a socket.



This is typical of servers running inetd, but you are not telling us about this context.

You can change the tags: this is a UNIX socket question, but has nothing to do with C ++.

0


source


You are getting this error because the file descriptor is 0

usually standard input, not a socket. I'm not sure what the original author intended, but it shouldn't work the way it is. Perhaps in another context I can help you.

0


source







All Articles