Skip to content

Instantly share code, notes, and snippets.

@dfukunaga
Last active April 12, 2017 14:38
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 dfukunaga/6c0628fe0ad9790fe7a1fbc5cba9b13c to your computer and use it in GitHub Desktop.
Save dfukunaga/6c0628fe0ad9790fe7a1fbc5cba9b13c to your computer and use it in GitHub Desktop.
get socket's local address and foreign address
#include <arpa/inet.h>
#include <netinet/in.h>
#include <sys/socket.h>
#include <string>
std::string get_local_addr(int sockfd) {
struct sockaddr_in sin;
socklen_t len = sizeof(sin);
int rc = getsockname(sockfd, (struct sockaddr*)&sin, &len);
if (rc != 0) {
// error
return "";
}
std::string host(inet_ntoa(sin.sin_addr));
int port = ntohs(sin.sin_port);
return host + ':' + std::to_string(port);
}
std::string get_foreign_addr(int sockfd) {
struct sockaddr_in sin;
socklen_t len = sizeof(sin);
int rc = getpeername(sockfd, (struct sockaddr*)&sin, &len);
if (rc != 0) {
// error
return "";
}
std::string host(inet_ntoa(sin.sin_addr));
int port = ntohs(sin.sin_port);
return host + ':' + std::to_string(port);
}
#include <iostream>
int main(int argc, char** argv) {
struct sockaddr_in sin;
sin.sin_family = AF_INET;
inet_aton(argv[1], &sin.sin_addr);
sin.sin_port = htons(atoi(argv[2]));
int sockfd = socket(AF_INET, SOCK_STREAM, 0);
connect(sockfd, (struct sockaddr*)&sin, sizeof(sin));
std::cout << "Local Address: " << get_local_addr(sockfd) << std::endl;
std::cout << "Foreign Address: " << get_foreign_addr(sockfd) << std::endl;
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment