Crabtree, Chad wrote:
Hello I am having a dikens of a time getting my IP address on the machine
that I am working on. I've looked in the mailing list and I found something
that I've been toying with but still I cannot get the xxx.xxx.xxx.xxx style
name I can only get my machine name. Here's what I have which I can get the
names but not the byte code address.
I know how to do this in python gethostbyname(gethostname()) by I'm having a
hard time with this.
program get_ip;
uses sockets,winsock;
const
len:integer=256;
var lsock,y,z:longint;
ac: array[0..255] of char;
phe:phostent;
xs:pchar;
Adder:TInetSockAddr;



begin writeln(gethostname(ac,len));
writeln(ac);
phe:=gethostbyname(ac);
xs:=phe^.h_addr_list[1];
writeln(xs);
phe:=gethostbyaddr(ac,4,PF_INET);
xs:=phe^.h_name;
writeln(xs)

end.
I'm attaching some quick&dirty hacks of your code that make everything working. It will also work on Linux (and other UNIXes, probably) when you replace winsock with Libc (in fact, I was doing my fixes while sitting on Linux... but I just checked this on Windows and it works). Note that it may return as address '127.0.0.1' which may or may not be usable to you.

--
Michalis
program get_ip;

uses sockets, Libc, SysUtils;

type
  TABCD=packed record a,b,c,d:Byte end;
  PABCD=^TABCD;

const
        len:integer=256;
var 
        ac: array[0..255] of char;
        phe:phostent;
        xs:pchar;
        i:Integer;
        abcd:TABCD;
begin 
        writeln(gethostname(ac,len)); { should return 0 = no error }
        writeln(ac);
        
        phe:=gethostbyname(ac);
        Writeln(phe^.h_length); { should be 4, inet address }
        
        { you should check h_addrtype to be sure that it's Internet address }
        
        { phe^.h_addr_list[0] shouldn't be nil, one address should be available }
       
        abcd:=PABCD(phe^.h_addr_list[0])^;
        
        Writeln(Format('%d.%d.%d.%d', [abcd.a, abcd.b, abcd.c, abcd.d]));
               
        phe:=gethostbyaddr(phe^.h_addr_list[0],4,PF_INET);
        if phe=nil then 
         Writeln('gethostbyaddr returned error') else
        begin
         xs:=phe^.h_name;
         writeln(xs)
        end;
end.

Reply via email to