gethostbyaddr()

Chris Kaynor ckaynor at zindagigames.com
Mon Jul 28 23:42:52 CEST 2014


On Mon, Jul 28, 2014 at 2:33 PM, Edward Manning <ejmmanning at gmail.com>
wrote:

> I wrote this code, but it seem to work fine if I only have one ip in the
> file. When I have more than one IP in the file
>
> I get a error. Does anyone have an idea why.
>

It would be helpful to know what the error you are getting is. It is also a
good idea to generally provide the Python version and OS version with your
messages, as they can often make a major difference. As it is, I've made my
best guess below (in bold), I've also included some other notes that may
cause issues, but I doubt are causing your error.


> import socket
>
>
>
>
>
> def main():
>
>
>
>     # get file names
>
>     infileName = input ("What file our the IP adderss in?  ")
>
>     outfileName = input("What file should the results go in?")
>
>
>
>     # open files
>
>     infile = open(infileName, "r")
>
>     outfile = open(outfileName, "w")
>

While this shouldn't cause the issue your reporting (without other issues
going on), Its generally a better idea to use the with statement to open
file, like so:
with open(infileName, "r") as infile:
    # code that needs infile goes here.

This will ensure that the file is closed when you are done with it, even if
an error occurs in the code that may prevent the code from running to
completion.


>
>
>
>
>     #Proccess each line of the input file
>
>
>
>     for line in infile:
>
>         ipAddress = line.strip()
>

I'm guessing that, when you only have one IP, you do not have a trailing
new-line in the file, but when you put more than one in the file, you have
a trailing new-line. You can try adding:

if not ipAddress:
    continue

here to ignore any empty lines (due to the line.strip() above, it will also
ignore all white-space lines) you might get. This may be the cause of your
error...


>         resluts = socket.gethostbyaddr(ipAddress)
>
>         print(resluts[0],resluts[2], end="")
>

Note that this does not seem to be printing into outfile (its printing to
stdout instead). I presume this is for debugging purposes.


> --
> https://mail.python.org/mailman/listinfo/python-list
>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20140728/17e7f2b3/attachment.html>


More information about the Python-list mailing list