Solved

How to get hostname with winsock?

Posted on 2001-06-14
16
598 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
  • 5
  • 5
  • 3
  • +3
16 Comments
 
LVL 4

Expert Comment

by:prashant_n_mhatre
Comment Utility
visit:

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

You'll get all information.
0
 
LVL 2

Expert Comment

by:GloriousRain
Comment Utility
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
Comment Utility
>>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
 

Author Comment

by:desktop2
Comment Utility
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
Comment Utility
Show your code...
0
 
LVL 32

Expert Comment

by:jhance
Comment Utility
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
Comment Utility
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
Comment Utility
OK, so your hostname is "My Computer".  

Change it and you'll get a different answer.....
0
How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

 

Author Comment

by:desktop2
Comment Utility
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
Comment Utility
>>>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
Comment Utility
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
Comment Utility
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
Comment Utility
jaisjoy,
Have you read the other comments I have posted on your other proposed answers.
0
 
LVL 30

Expert Comment

by:Axter
Comment Utility
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
Comment Utility
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
Comment Utility
jaisjoy,

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

Featured Post

How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

Join & Write a Comment

Suggested Solutions

In days of old, returning something by value from a function in C++ was necessarily avoided because it would, invariably, involve one or even two copies of the object being created and potentially costly calls to a copy-constructor and destructor. A…
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…
The goal of the tutorial is to teach the user how to use functions in C++. The video will cover how to define functions, how to call functions and how to create functions prototypes. Microsoft Visual C++ 2010 Express will be used as a text editor an…
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.

763 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

Need Help in Real-Time?

Connect with top rated Experts

10 Experts available now in Live!

Get 1:1 Help Now