1

when I try to connect to a webserver, my "FritzBox" (residential gateway device) is configured to block all connections that connect directly to an IP, not a host name. However, the connect() function only lets me connect using an IP address. How can I connect() to a server using the host name (the way web browsers do)?

Many thanks.

Wolfgang Fahl
  • 15,016
  • 11
  • 93
  • 186
KungPhoo
  • 516
  • 4
  • 18
  • There is no such thing as a connection that connects to a hostname. Please amend your question to describe the actual configuration. – user207421 May 18 '15 at 09:48

2 Answers2

2

... my "FritzBox" (residential gateway device) is configured to block all connections that connect directly to an IP, not a host name...

It looks like you are trying to bypass the settings of the child protection feature of the Fritzbox. What these settings mean in reality is that it will only allow HTTP connections which have a real hostname inside the Host-header of the HTTP-Request and not connections containing an IP only, i.e. it will allow http://example.com/ but not http://10.10.10.10/. For an example of the Host header look at the HTTP example request at Wikipedia.

Steffen Ullrich
  • 114,247
  • 10
  • 131
  • 172
  • It seems my HTTP request was misspelled. I can't reproduce it anymore. I forgot a space between "Host:" and "www...". Also I used HTTP/1.0, not HTTP/1.1 Many thanks. – KungPhoo May 19 '15 at 09:37
1

First of all connections are always connecting to an IP address, not a host name. So your gateway is doing something else than what you're telling us, it can't tell the difference on how a client connects to something. What it could do is inspect certain protocols specifically, e.g. look for a Host: header in HTTP requests.

But to answer your question: You need to look up the host name with DNS and convert it to an IP address. This can be done all in one go by the getaddrinfo() function, getaddrinfo() will perform lookups in a platform specific way by e.g. looking at host files and/or do DNS lookups: e.g.

int clientfd;  
struct addrinfo hints, *servinfo, *p;
int rc;
const char *port = "80";
const char *host = "www.google.com";

memset(&hints, 0, sizeof hints);
hints.ai_family = AF_UNSPEC;
hints.ai_socktype = SOCK_STREAM;

if ((rc = getaddrinfo(host, port, &hints, &servinfo)) != 0) {
    fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(rv));
    exit(1);
}

// getaddrinfo() can map the name to several IP addresses
for(p = servinfo; p != NULL; p = p->ai_next) {
    if ((clientfd= socket(p->ai_family, 
                  p->ai_socktype,p->ai_protocol)) == -1) {
        perror("socket()");
        continue;
    }

    if (connect(clientfd, p->ai_addr, p->ai_addrlen) == -1) {
        close(sockfd);
        continue;
    }

    break; //got a connection
}

if (p == NULL) {
    fprintf(stderr, "connect() failed\n");
    exit(2);
}

freeaddrinfo(servinfo);

//use clientfd
nos
  • 223,662
  • 58
  • 417
  • 506