net/SocketDescriptor: add method GetPeerCredentials()

This commit is contained in:
Max Kellermann 2018-08-20 16:11:17 +02:00
parent 50c7337965
commit 0ebba73cb8
2 changed files with 40 additions and 0 deletions

View File

@ -220,6 +220,32 @@ SocketDescriptor::GetError()
: errno;
}
size_t
SocketDescriptor::GetOption(int level, int name,
void *value, size_t size) const
{
assert(IsDefined());
socklen_t size2 = size;
return getsockopt(fd, level, name, (char *)value, &size2) == 0
? size2
: 0;
}
#ifdef HAVE_STRUCT_UCRED
struct ucred
SocketDescriptor::GetPeerCredentials() const noexcept
{
struct ucred cred;
if (GetOption(SOL_SOCKET, SO_PEERCRED,
&cred, sizeof(cred)) < sizeof(cred))
cred.pid = -1;
return cred;
}
#endif
#ifdef _WIN32
bool

View File

@ -150,6 +150,20 @@ public:
int GetError();
/**
* @return the value size or 0 on error
*/
size_t GetOption(int level, int name, void *value, size_t size) const;
#ifdef HAVE_STRUCT_UCRED
/**
* Receive peer credentials (SO_PEERCRED). On error, the pid
* is -1.
*/
gcc_pure
struct ucred GetPeerCredentials() const noexcept;
#endif
bool SetOption(int level, int name, const void *value, size_t size);
bool SetBoolOption(int level, int name, bool _value) {