-
October 15th, 2009, 04:10 PM
#1
Getting IP Address
Hello. I am new to Python, and what I am trying to do is having a script that gets my IP address and prints it out to the console.
I started with something like this:
Code:
import os
import sys
import urllib.request
fp = urllib.request.urlopen("http://en.myip.dk/Sq9UAWDCF8r3.aspx")
html = fp.read()
That's as far as I came. When I try to find a sub string I always get an error message.
E.g.: When I try to do
Code:
mystr = html.find(" is: ")
I get an error saying "TypeError: expected an object with the buffer interface."
I am using Python 3.1
Does anybody know why I do get this error and/or how do I get to the IP address?
Any help is appreciated.
-
October 16th, 2009, 09:00 AM
#2
Re: Getting IP Address
Never mind. I figured it out. All I had to do was this:
Code:
mystr = html.decode("utf-8")
That allowed me to use regular string functions on 'mystr'.
In case anybody is interested, the whole script looks like this:
Code:
import os
import sys
import urllib.request
fp = urllib.request.urlopen("http://en.myip.dk/Sq9UAWDCF8r3.aspx")
f = open('ipaddress.txt','w')
html = fp.read()
mystr = html.decode("utf-8")
index = mystr.find("is:")
ipone = mystr[index+4:]
iptwo = ipone.find("</title>")
address = ipone[:iptwo]
f.write(address)
f.close()
It fetches the IP address and writes it into a text file.
I am sure there must be 'cleaner' ways to do this, yet it works for me.
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|