Ottenere il nome dell'host corrispondente ad un indirizzo IP e viceversa

Da Gambas-it.org - Wikipedia.

Ottenere il nome (se esistente) dell'host corrispondente ad un indirizzo IP

Library "libc:6"

Public Struct in_addr
  s_addr As Integer
End Struct

Public Struct hostent
  h_name As Pointer
  h_aliases As Pointer
  h_addrtype As Integer
  h_length As Integer
  h_addr_list As Pointer
End Struct

Private Const AF_INET As Integer = 2

' int inet_aton(const char *cp, struct in_addr *inp)
' Converts the Internet host address cp from the IPv4 numbers-and-dots notation into binary form.
Private Extern inet_aton(cp As String, inp As In_addr) As Integer

' struct hostent *gethostbyaddr (const void *__addr, __socklen_t __len, int __type)
' Returns a structure of type hostent for the given host address addr of length len and address type type.
Private Extern gethostbyaddr(__addr As In_addr, __len As Integer, __type As Integer) As Hostent


Public Sub Main()

 Dim ipstr As String
 Dim ip As New In_addr
 Dim hp As Hostent

' Esempio pratico:
 ipstr = "127.0.0.1"

 If inet_aton(ipstr, ip) < 1 Then Error.Raise("Errore !")

 hp = gethostbyaddr(ip, SizeOf(TypeOf(ip.s_addr)), AF_INET)
 If IsNull(hp) Then Error.Raise("Errore !")
 
 Print "Nome associato all'IP "; ipstr; " = \e[31m"; String@(hp.h_name)
 
End


Ottenere l'indirizzo IP dal nome (se esistente) dell'host

Library "libc:6"

Public Struct hostent
  h_name As Pointer
  h_aliases As Pointer
  h_addrtype As Integer
  h_length As Integer
  h_addr_list As Pointer
End Struct

' struct hostent *gethostbyname(const char *name)
' Returns a structure of type hostent for the given host name.
Private Extern gethostbyname(idn As String) As Pointer


Public Sub Main()

 Dim host As Hostent
 Dim idn As String

' Esempio pratico:
 idn = "localhost"

 host = gethostbyname(idn)
 If isNull(host) Then ErrorRaise("Errore !")

 Print "IP associato al nome "; idn; " = \e[31m"; String@(Pointer@(host.h_addr_list) + 32)

End