Reputation: 5118
I've got process that listen to unix socket. However, before i read, i'd like to check some meta data about this incoming message such as it's source process (say i'd like to drop messages from non trusted senders). is there any syscall that retrieve this information.
if(listen(sock_fd, 10) != 0) {
assert("listen failed");
}
while((conn_fd = accept(sock_fd,
(struct sockaddr *) &address,
&address_length)) != -1) {
int nbytes = 0;
static char buffer[PAYLOAD_SZ];
nbytes = (int)read(conn_fd, buffer, PAYLOAD_SZ);
Upvotes: 1
Views: 1743
Reputation: 5118
After doing some research, I've found the answer that is most suitable for my needs.
using getsockopt
i was able to get the peer pid.
getsockopt(fd,SOCK_STREAM, LOCAL_PEERPID, &pid, &pid_len);
using this function i'm also capable to collect peer credentials, and more. just need to verify that the peer doesn't close the socket when this query is sent.
Upvotes: 6
Reputation: 1395
getpeername()
may be what you are looking for. Example code :
// assume s is a connected socket
socklen_t len;
struct sockaddr_storage addr;
char ipstr[INET6_ADDRSTRLEN];
int port;
len = sizeof addr;
getpeername(s, (struct sockaddr*)&addr, &len);
// deal with both IPv4 and IPv6:
if (addr.ss_family == AF_INET) {
struct sockaddr_in *s = (struct sockaddr_in *)&addr;
port = ntohs(s->sin_port);
inet_ntop(AF_INET, &s->sin_addr, ipstr, sizeof ipstr);
} else { // AF_INET6
struct sockaddr_in6 *s = (struct sockaddr_in6 *)&addr;
port = ntohs(s->sin6_port);
inet_ntop(AF_INET6, &s->sin6_addr, ipstr, sizeof ipstr);
}
printf("Peer IP address: %s\n", ipstr);
printf("Peer port : %d\n", port);
Upvotes: -1
Reputation: 783
For linux kernel 3.3 and its later versions, you have the command line ss -xp
.
This question on Unix & Linux has a good discussion and answers that might help you understand.
Upvotes: 0