hostname to ip
Posted: Thu Feb 07, 2013 1:06 pm
Hi, I need to convert hostname to ip in Linux, how can I do this? Snx in advance.
Code: Select all
CompilerIf Defined(HOSTENT, #PB_Structure) = #False
Structure hostent
*h_name
*h_aliases
h_addrtype.L
h_length.L
*h_addr_list
EndStructure
CompilerEndIf
InitNetwork()
Procedure GetIPAddressesFromHostname(Hostname.S)
Protected *HostInfos.hostent
Protected *HostnameBuffer
*HostNameBuffer = AllocateMemory(StringByteLength(Hostname, #PB_Ascii))
PokeS(*HostnameBuffer, Hostname, MemorySize(*HostnameBuffer), #PB_Ascii)
*HostInfos = gethostbyname_(*HostnameBuffer)
FreeMemory(*HostnameBuffer)
If *HostInfos = 0
Debug "Error: unable to find host name!"
Else
Debug "Hostname: " + PeekS(*HostInfos\h_name, -1, #PB_Ascii)
If *HostInfos\h_length = 4
IPType = #PB_Network_IPv4
Else
IPType = #PB_Network_IPv6
EndIf
Debug "IP addresses:"
*IP = *HostInfos\h_addr_list
While PeekI(*IP) <> 0
Debug IPString(PeekI(PeekI(*IP)), IPType)
*IP + SizeOf(Integer)
Wend
EndIf
Debug ""
EndProcedure
GetIPAddressesFromHostname("www.google.com")
GetIPAddressesFromHostname("www.purebasic.com")
Code: Select all
gethostbyname_(*HostnameBuffer)
No, it's a Unix API function. But the core of MacOS X is a BSD Unix, therefore most Unix API functions also work for MacOS X...Bisonte wrote:the functionis crossplatform ???Code: Select all
gethostbyname_(*HostnameBuffer)
And it is a windows-APIShardik wrote:No, it's a Unix API function. But the core of MacOS X is a BSD Unix, therefore most Unix API functions also work for MacOS X...
Too slow...ts-soft wrote:And it is a windows-API
Code: Select all
buffer_p = AllocateMemory(Len(name)+1)
PokeS(buffer_p,name,-1,#PB_Ascii)
bip_p = gethostbyname_(buffer_p)
FreeMemory(buffer_p)
If bip_p <> 0
ProcedureReturn PeekL(PeekL(PeekL(bip_p+12)))
Else
ProcedureReturn 0
EndIf
Your BIP (the result your procedure returns) is the first IP address of the requested host name. In order to work on a 64 bit OS you have to changeblueznl wrote:Anyway, the above works fine on Win32 but not on Win64. I suspect it's the PeekL stuff...
In other words, how to retrieve the BIP (not the IP) from a name on Win64?
Code: Select all
ProcedureReturn PeekL(PeekL(PeekL(bip_p+12)))
Code: Select all
ProcedureReturn PeekI(PeekI(PeekI(bip_p+24)))
Code: Select all
InitNetwork()
Procedure Get1stIPAddressOfHostName(name.S)
buffer_p = AllocateMemory(Len(name)+1)
PokeS(buffer_p,name,-1,#PB_Ascii)
*bip_p.HOSTENT = gethostbyname_(buffer_p)
FreeMemory(buffer_p)
If *bip_p <> 0
ProcedureReturn PeekI(PeekI(*bip_p\h_addr_list))
Else
ProcedureReturn 0
EndIf
EndProcedure
MessageRequester("Info", "1st IP address of www.purebasic.com: " +
IPString(Get1stIPAddressOfHostName("www.purebasic.com"), #PB_Network_IPv4))
Winsock API follows POSIX socket implementation to very high extent, up to some hassle regarding initialization and cleanup.Bisonte wrote:I'm impressedThe first API call that does on all OS the same ...