[Okta Webinar] Learn how to a build a cloud-first strategyRegister Now

x
?
Solved

C/C++ : How to retrieve a machine name from IP address?

Posted on 2008-11-19
7
Medium Priority
?
868 Views
Last Modified: 2012-05-05
Hi,

Could you please tell me how to retrieve the machine name using its IP address. I know if I have machine name I can retrieve IP address using gethostbyname but is there any way to retrieve machine name if I have IP address? The problem here is when client connect to server, server will have client IP address but I want  to display client's machine name along with IP address. For that I need to get the machine name from IP address. I think there must be some way to get this using DNS lookup but I am not sure,.

Thanks.
0
Comment
Question by:deshaw
  • 4
  • 3
7 Comments
 
LVL 86

Accepted Solution

by:
jkr earned 1000 total points
ID: 22997464
You'd use 'gethostbyaddr()' (http://msdn.microsoft.com/en-us/library/ms738521.aspx) in that case. E.g. (like on the MSDN page):
#include <winsock2.h>
#include <ws2tcpip.h>
#include <stdio.h>
 
int main(int argc, char **argv)
{
 
    //-----------------------------------------
    // Declare and initialize variables
    WSADATA wsaData;
    int iResult;
 
    DWORD dwError;
 
    struct hostent *remoteHost;
    char *host_name;
    struct in_addr addr;
 
    // Validate the parameters
    if (argc != 2) {
        printf("usage: %s ipv4 address\n", argv[0]);
        printf("  to return the host\n");
        printf("       %s 127.0.0.1\n", argv[0]);
        return 1;
    }
    // Initialize Winsock
    iResult = WSAStartup(MAKEWORD(2, 2), &wsaData);
    if (iResult != 0) {
        printf("WSAStartup failed: %d\n", iResult);
        return 1;
    }
 
    host_name = argv[1];
 
// If the user input is an alpha name for the host, use gethostbyname()
// If not, get host by addr (assume IPv4)
    if (isalpha(host_name[0])) {        /* host address is a name */
        printf("Calling gethostbyname with %s\n", host_name);
        remoteHost = gethostbyname(host_name);
    } else {
        printf("Calling gethostbyaddr with %s\n", host_name);
        addr.s_addr = inet_addr(host_name);
        if (addr.s_addr == INADDR_NONE) {
            printf("The IPv4 address entered must be a legal address\n");
            return 1;
        } else
            remoteHost = gethostbyaddr((char *) &addr, 4, AF_INET);
    }
 
    if (remoteHost == NULL) {
        dwError = WSAGetLastError();
        if (dwError != 0) {
            if (dwError == WSAHOST_NOT_FOUND) {
                printf("Host not found\n");
                return 1;
            } else if (dwError == WSANO_DATA) {
                printf("No data record found\n");
                return 1;
            } else {
                printf("Function failed with error: %ld\n", dwError);
                return 1;
            }
        }
    } else {
        printf("Function returned:\n");
        printf("\tOfficial name: %s\n", remoteHost->h_name);
        printf("\tAlternate names: %s\n", remoteHost->h_aliases);
        printf("\tAddress type: ");
        switch (remoteHost->h_addrtype) {
        case AF_INET:
            printf("AF_INET\n");
            break;
        case AF_INET6:
            printf("AF_INET\n");
            break;
        case AF_NETBIOS:
            printf("AF_NETBIOS\n");
            break;
        default:
            printf(" %d\n", remoteHost->h_addrtype);
            break;
        }
        printf("\tAddress length: %d\n", remoteHost->h_length);
        addr.s_addr = *(u_long *) remoteHost->h_addr_list[0];
        printf("\tFirst IP Address: %s\n", inet_ntoa(addr));
    }
 
    return 0;
}

Open in new window

0
 
LVL 1

Author Comment

by:deshaw
ID: 22997590
Will it works only for IPV4 addresses and not for APV6 addresses?

Thanks,
0
 
LVL 86

Expert Comment

by:jkr
ID: 22997620
Well, 'gethostbyaddr()' works for both address families, depending on which parameter you pass as the last parameter - that can be AF_INET for IPv4 or AF_INET6 for IPv6.
0
What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

 
LVL 1

Author Comment

by:deshaw
ID: 22997734
Could you tell me why second argument is only 4 gethostbyaddr((char *) &addr, 4, AF_INET)?
0
 
LVL 1

Author Comment

by:deshaw
ID: 22997745
How would I will get whether machine has IPV4 or IPV6 addresses then?

Thanks,
0
 
LVL 86

Expert Comment

by:jkr
ID: 22997799
'4' is the length, in bytes, of the address. That should better be written as

gethostbyaddr((char *) &addr, sizeof(addr), AF_INET);

You can tell what address family the remote host belongs to when you get an error code returned, indicating that it is the other address family on the remote side.
0
 
LVL 1

Author Closing Comment

by:deshaw
ID: 31518394
Thanks ikr.
0

Featured Post

Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

When writing generic code, using template meta-programming techniques, it is sometimes useful to know if a type is convertible to another type. A good example of when this might be is if you are writing diagnostic instrumentation for code to generat…
This article shows you how to optimize memory allocations in C++ using placement new. Applicable especially to usecases dealing with creation of large number of objects. A brief on problem: Lets take example problem for simplicity: - I have a G…
The viewer will learn how to user default arguments when defining functions. This method of defining functions will be contrasted with the non-default-argument of defining functions.
The viewer will learn how to clear a vector as well as how to detect empty vectors in C++.

867 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question