summaryrefslogtreecommitdiff
path: root/ip.c
blob: da99afd8849315f490ab0355f968966b47bebac2 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
#include <sys/types.h>
#include <arpa/inet.h>
#include <sys/socket.h>
#include <netdb.h>
#include <netinet/in.h>
#include <stdio.h>
#include <stdlib.h>
#include <stddef.h>
#include <string.h>
#include "ip.h"
#define HNAME "rskrf.ru"
static struct addrinfo hints;
static struct addrinfo *result, *rp;
static char ip[INET_ADDRSTRLEN];
static int s;
char *get_ip(size_t len)
{
	if (len != INET_ADDRSTRLEN) {
		fprintf(stderr, "get_ip: len must be %d\n", INET_ADDRSTRLEN);
		exit(EXIT_FAILURE);
	}
	memset(&hints, 0, sizeof(hints));
	hints.ai_family = AF_INET;
	hints.ai_flags = AI_ADDRCONFIG;	/* ret IPv4 only if system has IPv4 addr */
	hints.ai_socktype = SOCK_STREAM;
	hints.ai_protocol = IPPROTO_TCP;
	s = getaddrinfo(HNAME, "https", &hints, &result);
	if (s != 0) {
		fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(s));
		exit(EXIT_FAILURE);
	}
	for (rp = result; rp != NULL; rp = rp->ai_next) {
		inet_ntop(AF_INET,
			  &((struct sockaddr_in *)(rp->ai_addr))->sin_addr,
			  ip, INET_ADDRSTRLEN);
	}
	freeaddrinfo(result);
	return ip;
}