Skip to content

Instantly share code, notes, and snippets.

@h4k1m0u
Created May 11, 2022 19:07
Show Gist options
  • Save h4k1m0u/1eeb57378f93e796efe29ae83eb35348 to your computer and use it in GitHub Desktop.
Save h4k1m0u/1eeb57378f93e796efe29ae83eb35348 to your computer and use it in GitHub Desktop.
Get ip address by url
#include <stdio.h>
#include <string.h>
#include <sys/socket.h>
#include <netdb.h>
#include <arpa/inet.h>
#include <netinet/in.h>
/**
* Find ipv4 addresses (tcp) associated with given hostname
* Inspired by: https://www.inetdoc.net/dev/socket-c-4and6/socket-c-4and6.getaddrinfo.html
* See also example in: https://man7.org/linux/man-pages/man3/getaddrinfo.3.html
*
* Reference:
* - Beej's Guide to Network Programming: https://beej.us/guide/bgnet/
*/
int main(int argc, char* argv[]) {
// port=NULL => the port number of the returned socket addresses will be left uninitialized
// char* hostname = "www.google.com";
char* hostname = "www.soundcloud.com";
char* port = NULL;
typedef struct addrinfo addrinfo;
// hints used to filters out returned addresses (its unset fields must contain 0 or NULL)
addrinfo hints;
memset(&hints, 0, sizeof(hints));
hints.ai_family = AF_UNSPEC; // ipv4
hints.ai_socktype = SOCK_STREAM; // tcp
// returns a linked list bcoz same network could be accessible from tcp/udp, ipv4/ipv6...
addrinfo* results;
int ret = getaddrinfo(hostname, port, &hints, &results);
if (ret != 0) {
printf("Error while getting the addresses: %s\n", gai_strerror(ret));
return 1;
}
// loop through found addresses
addrinfo* result;
for (result = results; result != NULL; result = result->ai_next) {
// get address
struct sockaddr* address = result->ai_addr;
struct sockaddr_in* address_in = (struct sockaddr_in *) address;
struct in_addr ip_address = address_in->sin_addr;
// used instead of inet_ntoa() as it's obsolete
char address_str[INET_ADDRSTRLEN];
inet_ntop(AF_INET, &ip_address, address_str, INET_ADDRSTRLEN);
// get protocol (tcp/udp)
struct protoent* protocol = getprotobynumber(result->ai_protocol);
// get family (ipv4 or ipv6)
char* family = (result->ai_family == AF_INET) ? "ipv4" : "ipv6";
printf("Address: %s, family: %s, protocol: %s \n", address_str, family, protocol->p_name);
}
// free allocated linked list
freeaddrinfo(results);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment