Python: Grab the A record of any URI?
Question
I basically want to implement something where you can type in any URI ( I probably will only deal with http ) and I want to return the A record of the domain in the URI, I want the server's IP address.
I know there's the ping command which most people use to look an ip address up, but I also know there's 'host' and 'dig' which are more specific.
Are there any native functions I can use that will do this for me? And if so, how lenient is that function in terms of what URI string it accepts and the structure it's in? I want to throw it:
- http://foo.com
- www.foo.com
- http://foo.com/baz.ext
And have basically anything return an IP address. If need be I can take care of the URI parsing ( so it's a consistent format when looked up ) myself, that's an extra plus though.
Solution
py> import urlparse,socket
py> p = urlparse.urlparse("http://stackoverflow.com/questions/1480183")
py> p
('http', 'stackoverflow.com', '/questions/1480183', '', '', '')
py> host=p[1]
py> ai=socket.gethostbyname(host)
py> socket.gethostbyname(host)
'69.59.196.211'