0

In python I need to get IP from hostname:

socket.gethostbyname('www.python.org') # returns ip good
socket.gethostbyname('http://python.org') # raises error

I need to deal with hostnames starting with 'http://' so I figured out a way to remake them like this:

a = 'http://python.org'
a.replace('http://', 'www.')
print a # Why does it print http://python.org ???

I'm not sure I do the right thing. Plz help me with translating this type of hostname to IP

4
  • What is b? It should be a.replace('http://', 'www.') Commented Jan 2, 2014 at 9:57
  • 1
    Also your idea is wrong, you should replace http:// with an empty string. www.python.org might point to a different IP than python.org. Commented Jan 2, 2014 at 10:01
  • You are editing a and printing b? Commented Jan 2, 2014 at 10:01
  • sry, my fault in this example. in code it's really a. But still not working Commented Jan 2, 2014 at 10:01

3 Answers 3

7

You want urlparse:

>>> import urlparse
>>> urlparse.urlparse('http://python.org')
ParseResult(scheme='http', netloc='python.org', path='', params='', query='', fragment='')
>>> urlparse.urlparse('http://python.org').netloc
'python.org'
>>> 

Oh, and yes, you don't need to add any "www" in front of the top-level domain.

Sign up to request clarification or add additional context in comments.

Comments

1

You should do it like this,

a = 'http://python.org'
a = a.replace('http://', 'www.')  
# a.replace() does not change the original string. it returns a new string (replaced version).
print a

Comments

-1

You have several problems.

1st. Error is raised, because http://stuff is not a valid domain. It is natural to expect an error.

2nd. b does not exists in the context you provided.

3rd. It is a dangerous thing to swap http:// for www. blindly. python.org and www.python.org are two different domains and they may point to different places!

You should use regular expressions or some other routines to extract the domain name from an URL, and use gethostbyname on it.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.