Toadums
Toadums

Reputation: 2812

How to detect your IP/name using gethostbyname()

is there a way to get the IP number from gethostname()?

We are randomly generating IP addresses for the computers in the lab we are in. We use gethostbyname(<random ip>) to get the IP of a computer.

What we want to do essentially is compare the ip that we get from gethostbyname() with what we get from gethostname().

We tried:

struct hostent* host;
char temp[MAX_LEN];
gethostname(temp, MAX_LEN);

host = gethostbyname(<random ip address>)

if(host->h_name == temp) printf("They are the same\n");

The problem is, is that host->h_name is '172.125.45.1' (i made that up) and temp is 'u-my_comp'

so we cant compare the strings cause one gives us the name of the computer (u-my_comp), and the other gives the ip...

Is there anyway to make these functions return the same type of value?

we have tried doing something like

gethostname(temp, 24)
temp_host = gethostbyname(temp)

in hopes that now we could compare temp_host->h_name with host->h_name...but yeah, that didnt work either.

Any ideas?

thanks!

Upvotes: 0

Views: 10541

Answers (2)

caf
caf

Reputation: 239321

gethostbyname() is for converting a hostname into a socket address. If the "hostname" you supply is a dotted-quad IPv4 address, that will be all you get in the h_name parameter of the result.

To convert a socket address back into a name what you want is the companion function gethostbyaddr() - except that you don't, because both gethostbyname() and gethostbyaddr() are deprecated. Instead, you should be using getaddrinfo() and getnameinfo().

For example:

#include <stdio.h>
#include <sys/socket.h>
#include <netdb.h>
#include <netinet/in.h>
#include <arpa/inet.h>

int main()
{
    struct sockaddr_in sa;
    char host[1024];
    int gni_err;

    sa.sin_family = AF_INET;
    sa.sin_port = 0;
    sa.sin_addr.s_addr = inet_addr("127.0.0.1");

    gni_err = getnameinfo((struct sockaddr *)&sa, sizeof sa, host, sizeof host, NULL, 0, NI_NAMEREQD | NI_NOFQDN);

    if (gni_err == 0) {
        printf("host is: %s\n", host);
    } else {
        fprintf(stderr, "Error looking up host: %s\n", gai_strerror(gni_err));
    }

    return 0;
}

Upvotes: 4

AntonyM
AntonyM

Reputation: 1604

If you call:

myhost = gethostbyname(temp);

(having allocated myhost) then you will have two hostent structures you will compare - you will have the IP address lists for both the target query host and the current host (not just the hostname for the current host).

Upvotes: 0

Related Questions