in reply to Domain name from ip.

If you have the hostname, it's just a matter of string manipulation to extract the domain.

The trick is knowing what counts as a domain.

With gTLDs (.com, .net, .org, etc.), it's easy: you just want the last two atoms of the hostname ...

my $domain = join( '.' => ( split /\./ => $host )[-1,-2] );

... but with ccTLDs (.uk, .jp, .us), things get a lot more tricky as many of those have their own .com equivalents (.co.uk) which should be considered to be the real domains, or -- worse still -- use a mix of the two and three level styles.

An imperfect approach could be...

my @atom = split /\./, $host; if ( length($atom[-1]) == 3 ) { # gTLD $domain = join( '.', @atom[-2,-1] ); } elsif ( length($atom[-1]) == 2 ) { # ccTLD # Check if ccTLD domains are name.x.tld or # name.tld style. This is /NOT/ 100% accurate! $domain = join '.' => $atom[-2] =~ /^(?:com?|net|org|ac|edu)$/ ? @atom[-3,-2,-1] : @atom[-2,-1]; } else { warn("Couldn't extract gTLD/ccTLD from $host\n"); $domain = undef; }

    --k.


Replies are listed 'Best First'.
Re: Re: Domain name from ip.
by Fastolfe (Vicar) on Dec 03, 2001 at 06:08 UTC
    Remembering of course that com|net|org|edu|gov|int aren't the only gTLD's anymore. :(
Re: Re: Domain name from ip.
by blax (Sexton) on Dec 03, 2001 at 07:48 UTC
    Kanji,

    That method would not work all of the time. Sometimes gethostbyaddr will return a hostname that looks something like this: HOST5-209.252.153.98.

    Thanks everyone for your help,
    <RB> blax