Skip to content

Instantly share code, notes, and snippets.

@alepez
Created May 12, 2015 15:48
Show Gist options
  • Save alepez/165267b8cabaecf88328 to your computer and use it in GitHub Desktop.
Save alepez/165267b8cabaecf88328 to your computer and use it in GitHub Desktop.
ipv4 sockaddr to human readable ip
#include <netdb.h>
#include <arpa/inet.h>
#include <iostream>
#include <cstring>
#include <stdexcept>
int main(int argc, char* argv[]) {
if (argc < 2) {
return 0;
}
const std::string host { argv[1] };
addrinfo hints { };
memset(&hints, 0, sizeof(addrinfo));
hints.ai_family = PF_UNSPEC;
hints.ai_flags = AI_ADDRCONFIG;
hints.ai_socktype = SOCK_STREAM;
addrinfo* ainfo;
int s = getaddrinfo(host.c_str(), NULL, &hints, &ainfo);
if (s) {
throw std::runtime_error(std::string(gai_strerror(s)) + " " + host);
}
char str[128];
inet_ntop(AF_INET, &(((sockaddr_in *) ainfo->ai_addr)->sin_addr), (char*) &str, sizeof(str));
std::cerr << host << " -> " << str << "\n";
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment