Reputation: 1031
In my linux c++ application I want to write a function hat will check for a giving socket if the socket peer is local. I know how to retrive all the local IPs, but I don't know how to check if the socket peer is from the local IPS list.
any help? with code please!!
10x
Upvotes: 0
Views: 594
Reputation: 59563
You are looking for getpeername()
for the peer side of the socket. Use getsockname()
for the local side of the socket. The following snippet will retrieve a sockets local and peer addresses in the Internet domain. I'll leave it up to you to extend it to handle other types of sockets if you have a need. I included some rudimentary error checking as a bonus.
int
get_addresses(int sd, struct sockaddr_in *local_ptr,
struct sockaddr_in *peer_ptr)
{
int rc = -1;
if (local_ptr == NULL || peer_ptr == NULL) {
errno = EFAULT;
return rc;
}
if (sd == -1) {
errno = EBADF;
return rc;
}
if (local_ptr->sin_family != AF_INET || peer_ptr->sin_family != AF_INET) {
errno = EINVAL;
return rc;
}
rc = getsockname(sd, (struct sockaddr*)local_ptr,
sizeof(struct sockaddr_in));
if (rc == 0) {
rc = getpeername(sd, (struct sockaddr*)local_ptr,
sizeof(struct sockaddr_in));
if (rc < 0) {
if (errno == ENOTCONN) {
/* socket is not connected so zero out the peer side */
peer_ptr->sin_len = sizeof(struct sockaddr_in);
peer_ptr->sin_family = AF_INET;
peer_ptr->sin_port = 0;
peer_ptr->sin_addr.s_addr = INADDR_NONE;
rc = 0;
}
}
}
return rc;
}
Upvotes: 1