0

hello i wanted to make my code when i needed to call back my function but because of my addr parameter i can't call it i will need help thanks

def send_magic_packet(addr):
    # create socket
    with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as s:
        s.setsockopt(socket.SOL_SOCKET, socket.SOBROADCAST, 1)
        # parse address
        mac = addr.upper().replace("-", "").replace(":", "")
        if len(mac) != 12:
            raise Exception("invalid MAC address format: {}".format(addr))
        buf = b'f' * 12 + (mac * 20).encode()
        # encode to magic packet payload
        magicp = b''
        for i in range(0, len(buf), 2):
            magicp += struct.pack('B', int(buf_[i:i + 2], 16))

        # send magic packet
        print("sending magic packet for: {}".format(addr))
        s.sendto(magicp, ('<broadcast>', DEFAULT_PORT))

while True:
    send_magic_packet(addr)
    data = aio.receive('feed')
    if int(data.value) == 0:
        print("PC Off")
    if int(data.value) == 1:
        print("PC ON")
Traceback (most recent call last):
  File "D:/Documents/WOL.py", line 42, in <module>
    send_magic_packet(addr)
NameError: name 'addr' is not defined

2 Answers2

2

Replace address while calling as a string or define it.

while True:
    addr = '192.168.2.323'
    send_magic_packet(addr)

or simply like this,

while True:
    send_magic_packet('192.168.2.323')
Vignesh
  • 1,553
  • 1
  • 10
  • 25
  • they said Traceback (most recent call last): File "D:/Documents/WOL.py", line 42, in send_magic_packet('192.168.1.98') File "D:/Documents/WOL.py", line 21, in send_magic_packet s.setsockopt(socket.SOL_SOCKET, socket.SOBROADCAST, 1) AttributeError: module 'socket' has no attribute 'SOBROADCAST' – rateur42 Jul 18 '20 at 17:42
1

You need to define addr outside of your function definition.

So, e.g.

def send_magic_packet(addr):
    # create socket
    with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as s:
        s.setsockopt(socket.SOL_SOCKET, socket.SOBROADCAST, 1)
        # parse address
        mac = addr.upper().replace("-", "").replace(":", "")
        if len(mac) != 12:
            raise Exception("invalid MAC address format: {}".format(addr))
        buf = b'f' * 12 + (mac * 20).encode()
        # encode to magic packet payload
        magicp = b''
        for i in range(0, len(buf), 2):
            magicp += struct.pack('B', int(buf_[i:i + 2], 16))

        # send magic packet
        print("sending magic packet for: {}".format(addr))
        s.sendto(magicp, ('<broadcast>', DEFAULT_PORT))

# Define addr
# -----------
addr = "foo"

while True:
    send_magic_packet(addr)
    data = aio.receive('feed')
    if int(data.value) == 0:
        print("PC Off")
    if int(data.value) == 1:
        print("PC ON")

G. Shand
  • 388
  • 3
  • 12