Ottenere gli indirizzi IP di ogni interfaccia presente sulla medesima macchina

Da Gambas-it.org - Wikipedia.

Per ottenere gli indirizzi IP di ogni interfaccia eventualmente presente sulla medesima macchina, è possibile utilizzare il seguente semplice codice:

Library "libc:6"

Public Struct sockaddr
  sa_ As Short
  sa_data[14] As Byte
End Struct

Public Struct sockaddr_in
  sin_ As Short
  sin_port As Short
  sin_addr As Integer
  sin_zero[8] As Byte
End Struct

Public Struct ifaddrs   ' /usr/include/ifaddrs.h
  ifa_next As Pointer
  ifa_name As Pointer
  ifa_flags As Integer
  ifa_addr As Pointer
  ifa_netmask As Pointer
  ifa_ifu As Pointer
  ifa_data As Pointer
End Struct

Private Const NI_NUMERICHOST As Integer = 1
Private Const AF_INET As Integer = 2
Private Const NI_MAXHOST As Integer = 1025
 
' int getifaddrs (struct ifaddrs **__ifap)
' Create a linked list of `struct ifaddrs' structures.
Private Extern getifaddrs(__ifap As Pointer) As Integer

' int getnameinfo (const struct sockaddr *__sa, socklen_t __salen, char * __host, socklen_t __hostlen, char * __serv, socklen_t __servlen, int __flags)
' Translate a socket address to a location and service name.
Private Extern getnameinfo(__sa As Sockaddr, __salen As Integer, __host As Pointer, __hostlen As Integer, __serv As Pointer, __servlen As Integer, __flags As Integer) As Integer

' const char *gai_strerror (int __ecode)
' Convert error return from getaddrinfo() to a string.
Private Extern gai_strerror(__ecode As Integer) As String


Public Sub Main()
 
 Dim ifa As Ifaddrs
 Dim i As Integer
 Dim host As New Byte[NI_MAXHOST]
 Dim sai As New Sockaddr_in
 Dim soad As Sockaddr
 Dim p As Pointer
 
 If getifaddrs(VarPtr(p)) == -1 Then Error.Raise("Errore !")
 
 ifa = p   ' [nota 1]
 
 While Not IsNull(ifa.ifa_next)
   soad = ifa.ifa_addr
   If soad.sa_ == AF_INET Then
     i = getnameinfo(ifa.ifa_addr, Object.SizeOf(sai), host.Data, NI_MAXHOST, 0, 0, NI_NUMERICHOST)
     If i > 0 Then Error.Raise("Errore: " & gai_strerror(i))
     Print "\e[0mInterfaccia: \e[1m"; String@(ifa.ifa_name); "\e[0m \tIndirizzo: \e[31m"; String@(host.Data)
   Endif
     ifa = ifa.ifa_next
 Wend
   
End


Note

[1] Per questa assegnazione di un Puntatore ad una Struttura vedere:


Riferimenti