1

I have a script that is given a bunch of local IPv4 addresses in a local network. I can get the hostnames of those IPs in Python2.7 via:

socket.gethostbyaddr(IP)

However, these hostnames (if resolved) return as something of the form:

hostname.local.companyname.com

The only piece of information I'm interested in with this value is hostname. I would like to remove the local.companyname.com domain name from the fully qualified hostname. I could find the aspects of all resolved hostnames in common and then remove them that way, but I'm wondering if there is there any way to directly query the local domain itself?

(edit: this is running on Ubuntu)

MikeFenton
  • 307
  • 2
  • 10

3 Answers3

3

For Default machine domain name Try:

import socket

def get_dns_domain():
    return socket.getfqdn().split('.', 1)[1]

print get_dns_domain()
Anonymous
  • 659
  • 6
  • 16
1

Ubuntu likes to put your local unqualified hostname in /etc/hosts with a loopback IP address like this:

127.0.1.1   ubuntu-pc

which makes it difficult to get your real IP and domain.

One solution is to use this answer to get your real (not loopback) IP address, and look this IP up and use its domain:

import socket
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.connect(("8.8.8.8", 80))
myip = s.getsockname()[0]
s.close()
fqdn = socket.gethostbyaddr(myip)[0]
domain = fqdn.split('.', 1)[1]
print 'myip:', myip
print 'fqdn:', fqdn
print 'domain:', domain

Which outputs something similar to:

myip: 192.168.1.33
fqdn: fred-pc.my.domain
domain: my.domain
Kim
  • 409
  • 3
  • 9
  • I already have IP addresses (given by network traffic). As I said in the question, I can get the domain name from `socket.gethostbyaddr(IP)`. I'm just trying to see if there are any other methods to exclusively get the domain, rather than parsing it out of the fully qualified domain name. – MikeFenton Jan 24 '19 at 10:03
1
>>> hostname = socket.gethostbyaddr(IP)[0].partition('.')[0]
>>> hostname
'myhost'

>>> hostname, domain = socket.gethostbyaddr(IP)[0].partition('.')[::2]
>>> hostname, domain
('myhost', 'here.example.com')
Greg Mueller
  • 506
  • 3
  • 7