Created
November 7, 2014 08:57
-
-
Save jhthorsen/e058dec38c7678259686 to your computer and use it in GitHub Desktop.
This example show how to get the peer username from a unix socket. (getpeereid SO_PEERCRED AF_UNIX)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# See also | |
# http://www.perlmonks.org/bare/?node_id=881003 | |
# http://www.freebsd.org/cgi/man.cgi?query=getpeereid | |
use strict; | |
use warnings; | |
use IO::Socket::UNIX; | |
use Socket qw( SO_PEERCRED SOL_SOCKET ); | |
if (@ARGV) { | |
IO::Socket::UNIX->new(Peer => $ARGV[0], Type => SOCK_STREAM, Timeout => 10) or die $@; | |
} | |
else { | |
my $socket = "/tmp/test-peer-id-socket"; | |
unlink $socket or die "rm $socket" if -e $socket; | |
my $server = IO::Socket::UNIX->new(Type => SOCK_STREAM, Local => $socket, Listen => SOMAXCONN); | |
die "Can't create UNIX socket: $!" unless $server; | |
print "Connect to server with: $^X $0 $socket\n"; | |
while(1) { | |
my $client = $server->accept or die "Cannot accept: $!"; | |
my ($pid, $uid, $gid) = unpack 'i*', getsockopt $client, SOL_SOCKET, SO_PEERCRED; | |
print "Peer socket user: pid=$pid, uid=$uid, gid=$gid\n"; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment