Ad

Entire Script Refuses To Execute When Include A While Loop?

- 1 answer

I'm trying to write a very basic script which gets the hostname of every device on the local network and prints the ip address of the hostname which matches my specification. however the code simply doesn't run. After a bit of trial and error, i realised that everything in the code works fine WITHOUT the while loop, but once it is included, it's as if nothing is even written in the file. I have no idea why this is happening

import socket, pyperclip
myPC = socket.gethostname()
hostName = ''
ipEnd = 0
while str(hostName[0]) != myPC:
    ipEnd += 1
    hostName = str(socket.gethostbyaddr('192.168.0.' + str(ipEnd)))
    pyperclip.copy('afterloop')
print(ipEnd)

EDIT: new code (still faulty) looks like this:

import socket, pyperclip
myPC = socket.gethostname()
hostName = 'placeholder'
ipEnd = 0
while hostName[0] != myPC:
    ipEnd += 1
    hostName = socket.gethostbyaddr('192.168.0.' + str(ipEnd))
    pyperclip.copy('afterloop')
print(ipEnd)
Ad

Answer

Some notes to try:

  1. Initialise the hostname with the first IP:
ip_end = 1
hostname = socket.gethostbyaddr('192.168.0.{}'.format(ip_end))

This will help avoid any strange behaviour at the start. As a side note I've changed your code slightly to be better in line with naming conventions/string formatting just for your knowledge.

  1. socket.gethostbyaddr returns a tuple of (hostname, aliaslist, ipaddrlist) however you are converting the entire thing into a str. This means that when you do hostname[0] you are only taking the first character of the string (in this case a ().

    Try changing your while loop to look something like

import socket, pyperclip
my_pc = socket.gethostname()
ip_end = 1
hostname = socket.gethostbyaddr('192.168.0.{}'.format(ip_end))[0]
while hostname != my_pc:
  ip_end += 1
  hostname = socket.gethostbyaddr('192.168.0.{}'.format(ip_end))[0]
  pyperclip.copy('afterloop')
print(ip_end)
Ad
source: stackoverflow.com
Ad