Solved

How to get hostname with winsock?

Posted on 2001-06-14
16
623 Views
Last Modified: 2011-09-20
I can use getpeername() and extract hostname (e.g. ppp345656.sympatico.com) for peer to which a socket is connected.

But how can I get same hostname for my computer? If I use gethostname() it returns name of my computer (e.g. "my comuter"), not my hostname.
0
Comment
Question by:desktop2
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 5
  • 5
  • 3
  • +3
16 Comments
 
LVL 4

Expert Comment

by:prashant_n_mhatre
ID: 6193505
visit:

http://www.vijaymukhi.com/vmis/vmchap4.htm

You'll get all information.
0
 
LVL 2

Expert Comment

by:GloriousRain
ID: 6193661
Two functions in VC++ here to get HostDomainName and HostName but not with winsock :(

#define _WIN32_WINNT 0x0500
#define _UNICODE
#define UNICODE

#include <windows.h>
#include <comdef.h>
#define BUF_SIZE 4096

bstr_t getHostDomainName() {

   HRESULT hr     = S_OK;
   BSTR   domainName;
   DWORD dwSize  = 0;
   wchar_t* pBuf = new wchar_t[BUF_SIZE];
   if(pBuf == NULL)
      _com_issue_error(E_OUTOFMEMORY);

   if(!GetComputerNameEx((COMPUTER_NAME_FORMAT)ComputerNameDnsDomain,
                     pBuf,
                     &dwSize)) {
      if(GetLastError() == ERROR_MORE_DATA) {
         delete [] pBuf;
         pBuf = new wchar_t[dwSize+1];
         if(pBuf == NULL)
            _com_issue_error(E_OUTOFMEMORY);

         if(!GetComputerNameEx((COMPUTER_NAME_FORMAT)ComputerNameDnsDomain, pBuf, &dwSize) ) {
            hr =   HRESULT_FROM_WIN32(GetLastError());
            delete [] pBuf;
            pBuf    = NULL;
            _com_issue_error(hr);
         }
      }
      else
         _com_issue_error(HRESULT_FROM_WIN32(GetLastError()));
   }

   domainName = SysAllocString(pBuf);
   delete [] pBuf;
   
   return bstr_t(domainName, false);
}



#define _WIN32_WINNT 0x0500
#define _UNICODE
#define UNICODE

#include <windows.h>
#include <comdef.h>
#define BUF_SIZE 4096

bstr_t getHostName() {

   HRESULT hr         = S_OK;
   BSTR   hostName;
   DWORD   dwSize      = 0;
   wchar_t* pBuf = new wchar_t[BUF_SIZE];
   if(pBuf == NULL)
      _com_issue_error(E_OUTOFMEMORY);

   if(!GetComputerNameEx((COMPUTER_NAME_FORMAT)ComputerNameDnsHostname,
                     pBuf,
                     &dwSize)) {
      if(GetLastError() == ERROR_MORE_DATA) {
         delete [] pBuf;
         pBuf = new wchar_t[dwSize+1];
         if(pBuf == NULL)
            _com_issue_error(E_OUTOFMEMORY);

         if(!GetComputerNameEx((COMPUTER_NAME_FORMAT)ComputerNameDnsHostname, pBuf, &dwSize) ) {
            hr =   HRESULT_FROM_WIN32(GetLastError());
            delete [] pBuf;
            pBuf    = NULL;
            _com_issue_error(hr);
         }
      }
      else
         _com_issue_error(HRESULT_FROM_WIN32(GetLastError()));
   }

   hostName = SysAllocString(pBuf);
   delete [] pBuf;
   
   return bstr_t(hostName, false);
}


0
 
LVL 32

Expert Comment

by:jhance
ID: 6195151
>>If I use gethostname() it returns name of my computer
(e.g. "my comuter"), not my hostname.

What makes you think the hostname of your computer is DIFFERENT from your computer name?  In most cases they are the same and in your specific case, this is also true.  gethostname() returns your hostname.
0
[Live Webinar] The Cloud Skills Gap

As Cloud technologies come of age, business leaders grapple with the impact it has on their team's skills and the gap associated with the use of a cloud platform.

Join experts from 451 Research and Concerto Cloud Services on July 27th where we will examine fact and fiction.

 

Author Comment

by:desktop2
ID: 6195959
Because I can get 2 different names:
1) "My Computer" (by gethostname())
2) "ppp345656.sympatico.com" (by WSAAsyncGetHostByAddr() which I run on 2nd computer to which my computer is connected by socket


And I can't run code above since GetComputerNameEx() require Win2K OS
0
 
LVL 32

Expert Comment

by:jhance
ID: 6196002
Show your code...
0
 
LVL 32

Expert Comment

by:jhance
ID: 6196074
Here's how I do it and it returns the hostname every time...


     WORD wver;
     WSADATA wsa;
     int err;
     char lpszHostname[32];
     wver = MAKEWORD(1, 1);
 
     if(!WSAStartup(wver, &wsa)){
          if(!gethostname(lpszHostname, 31)){
               SetDlgItemText(IDC_HOSTNAME, lpszHostname);
          }

          WSACleanup();
     }
0
 

Author Comment

by:desktop2
ID: 6196253
I'm using same code and hostname allways "My Computer" when I connected to the Internet and when not.

char aLocalHostName[100];
if(gethostname( aLocalHostName, 100))
  {aLocalHostName[0]='\0';
   return 0;
  }
MessageBox(0,aLocalHostName,"debug",MB_OK);
0
 
LVL 32

Expert Comment

by:jhance
ID: 6196308
OK, so your hostname is "My Computer".  

Change it and you'll get a different answer.....
0
 

Author Comment

by:desktop2
ID: 6197123
Yes if change computer name to rcomputer then gethostname() returns this name. It probably depends on internet bindings, settings etc.

And I actually needed hostname like ppp345656.sympatico.com by which I can connect to my computer from the Internet. I can't connect to my computer from the Internet by name "rcomputer" :-(
0
 
LVL 32

Accepted Solution

by:
jhance earned 100 total points
ID: 6197261
>>>ppp345656.sympatico.com

Now you're talking something different.  This is NOT your computer's hostname but I see where you might think it is.

ppp345656.sympatico.com is SYMPATICO.COM's hostname for the IP address that is assigned to your computer when it connects.  Now, there probably is a way to get what you want but it's more complex than just a couple of WINSOCK calls.  You need:

1) Use the RAS API to get the CURRENT IP address for your connection.

2) Use WINSOCK's gethostbyaddr() to resolve the IP address to the sympatico.com hostname.  Note that this ONLY works if there is an RDNS (REVERSE DNS) lookup for the IP block.  In most cases for an ISP, this is the case.
0
 

Author Comment

by:desktop2
ID: 6199039
Using RAS API is not the best solution for me becouse at work I'm connected by LAN , so I try to use WSAAsyncGetHostByName() to get current IP address from name of my computer (rcomputer), but it returns 2 different IP addresses for my computer. Which one should I use in gethostbyaddr()?
0
 

Expert Comment

by:jaisjoy
ID: 6201835
Hi you can try this

char szHostName[1024];
     char szHostIpAddress[16];
     memset ( szHostIpAddress , '\0' , sizeof ( szHostIpAddress) );
     gethostname( szHostName, sizeof(szHostName) );
     hostent *pHostInfo = gethostbyname( szHostName );
     if ( pHostInfo == NULL )
     {
          AfxMessageBox( "Error in retrieving host name" );
          return 0;
     }

     unsigned char ch1 = pHostInfo->h_addr_list[0][0];
     unsigned char ch2 = pHostInfo->h_addr_list[0][1];
     unsigned char ch3 = pHostInfo->h_addr_list[0][2];
     unsigned char ch4 = pHostInfo->h_addr_list[0][3];

     sprintf( szHostIpAddress, "%d.%d.%d.%d", ch1, ch2, ch3, ch4 );

good luck


0
 
LVL 30

Expert Comment

by:Axter
ID: 6201837
jaisjoy,
Have you read the other comments I have posted on your other proposed answers.
0
 
LVL 30

Expert Comment

by:Axter
ID: 6201842
Hi (desktop2):
Feel free to click the [Reject Answer] button near (Answer-poster's) response, even if it seems like a good answer.
Doing so will increase your chance of obtaining additional input from other experts.  Later, you can click the [Select Comment as Answer] button on any response.
0
 
LVL 30

Expert Comment

by:Axter
ID: 6201894
Hi (jaisjoy), welcome to EE.
All of the experts here, for the most part have learn from other experts as
to the proper etiquette for posting answer.

First-class etiquette for posting Answers:
1.  An answer should not be posted as an answer, if other experts have
previously posted possible answers as comments, and/or have already made
contributions to the question.

2.  An answer should not be posted as an answer, if it has a question.
Example: (Is this for windows? If so, here's the answer)

3.  An answer should not be posted as an answer, if it has the phrase "I
think".
Example:  (I think this should work)

4.  Full complete schoolwork answers must not be posted. (EE Policy)

5.  If you inadvertently post an answer after anther expert just post the
same answer as a comment, you should promptly notify the questioner of your
accidental post, and ask the questioner to fairly award the question to the
expert whom fully/best answered the question first.  You might consider
also apologizing to the other expert.

If you feel you have an answer, you can post it as a comment, and the
questioner can convert your comment to an answer if he/she thinks it's
correct or deserving of the awarded points.

There are many experts who never post answers as answer.  Instead, they
post their answers as comments.
If you read the following link, you'll see why this is the preferred method
for many of our valued experts, including myself.

http://www.experts-exchange.com/jsp/cmtyQuestAnswer.jsp

At the bottom of the above link, see the following section:
"Advice for Experts on Providing Solutions Through Comments or Answers"
0
 

Author Comment

by:desktop2
ID: 6208928
jaisjoy,

I'm using exactly same code , please read comments before yours
0

Featured Post

Industry Leaders: 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

This article will show you some of the more useful Standard Template Library (STL) algorithms through the use of working examples.  You will learn about how these algorithms fit into the STL architecture, how they work with STL containers, and why t…
Many modern programming languages support the concept of a property -- a class member that combines characteristics of both a data member and a method.  These are sometimes called "smart fields" because you can add logic that is applied automaticall…
The goal of the video will be to teach the user the concept of local variables and scope. An example of a locally defined variable will be given as well as an explanation of what scope is in C++. The local variable and concept of scope will be relat…
The viewer will learn how to clear a vector as well as how to detect empty vectors in C++.

636 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