Skip to content

Instantly share code, notes, and snippets.

@jhthorsen
Created November 7, 2014 08:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jhthorsen/e058dec38c7678259686 to your computer and use it in GitHub Desktop.
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)
# 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