Skip to content

Instantly share code, notes, and snippets.

@twslankard
Created May 31, 2011 20:24
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save twslankard/1001201 to your computer and use it in GitHub Desktop.
Save twslankard/1001201 to your computer and use it in GitHub Desktop.
getaddrinfo / inet_ntop example
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <arpa/inet.h>
#include <netdb.h>
int main(int argc, char * argv[]) {
struct addrinfo * _addrinfo;
struct addrinfo * _res;
char _address[INET6_ADDRSTRLEN];
int errcode = 0;
if(argc < 2) {
printf("Usage: %s [host]\n", argv[0]);
return EXIT_FAILURE;
}
errcode = getaddrinfo(argv[1], NULL, NULL, &_addrinfo);
if(errcode != 0) {
printf("getaddrinfo: %s\n", gai_strerror(errcode));
return EXIT_FAILURE;
}
for(_res = _addrinfo; _res != NULL; _res = _res->ai_next) {
if(_res->ai_family == AF_INET) {
if( NULL == inet_ntop( AF_INET,
&((struct sockaddr_in *)_res->ai_addr)->sin_addr,
_address,
sizeof(_address) )
) {
perror("inet_ntop");
return EXIT_FAILURE;
}
printf("%s\n", _address);
}
}
}
@Dauie
Copy link

Dauie commented Jul 13, 2018

Thank you for the example, sir. It helped a ton.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment