[fpc-pascal] RE: Get Local IP using glib (eth0,eth1)
Jeff Pohlmeyer
yetanothergeek at gmail.com
Fri Oct 6 04:38:53 CEST 2006
> I'm trying to write a function to read the local IP eth0/eth1
> using glibc library...
program ip_addr;
{$MODE OBJFPC}
uses libc;
const
IP_NAMESIZE = 16;
type
ipstr = array[0..IP_NAMESIZE-1] of char;
function GetIPAddressOfInterface( if_name:ansistring):ansistring;
var
ifr : ifreq;
tmp:ipstr;
sock : longint;
p:pChar;
begin
Result:='0.0.0.0';
strncpy( ifr.ifr_ifrn.ifrn_name, pChar(if_name), IF_NAMESIZE-1 );
ifr.ifr_ifru.ifru_addr.sa_family := AF_INET;
FillChar(tmp[0], IP_NAMESIZE, #0);
sock := socket(AF_INET, SOCK_DGRAM, IPPROTO_IP);
if ( sock >= 0 ) then begin
if ( ioctl( sock, SIOCGIFADDR, @ifr ) >= 0 ) then begin
p:=inet_ntoa( ifr.ifr_ifru.ifru_addr.sin_addr );
if ( p <> nil ) then strncpy(tmp, p, IP_NAMESIZE-1);
if ( tmp[0] <> #0 ) then Result := tmp;
end;
libc.__close(sock);
end;
end;
begin
if (ParamCount=1)
then WriteLn(GetIPAddressOfInterface(ParamStr(1)))
else WriteLn('Usage:', ParamStr(0), '<interface-name>')
end.
- Jeff
More information about the fpc-pascal
mailing list