Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
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