How to incorporate the IP address of a device into a Python script if the address changes

|▌冷眼眸甩不掉的悲伤 提交于 2019-12-13 20:34:15

问题


I have a Python script which retrieves the measured data from a smart plug so that I can visualize it on my Rasbperry Pi.

This command gets the data

send_hs_command("192.168.1.26", 9999, b'{"emeter":{"get_realtime":{}}}')

and this is the define

def send_hs_command(address, port, cmd):
    data = b""

    tcp_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    try:
        tcp_sock.connect((address, port))
        tcp_sock.send(encrypt(cmd))
        data = tcp_sock.recv(2048)
    except socket.error:        
        print(time.asctime( time.localtime(time.time()) ), "Socket closed.", file=sys.stderr)
    finally:
        tcp_sock.close()
    return data

My problem is that if I take the Smart Plug somewhere else, it will have a new IP-Address, which means I have to keep rewriting it on my Python script. This is not an option for me. What would be the simplest solution? Thanks


回答1:


I don't have a Pi to run this on.

If the IP address of the target(Smart Plug) is variable, can you not use a pre-determined host-name(located in '/etc/hostname') instead?

the socket library provides a few handy functions;

You can first use gethostbyaddr to get the host-name if you don't have the host-name information already. Then from that point onward you can use the known host-name and use create_connection to establish connections.

However, if you want to use something more dynamic; I'd suggest using the MAC address as the key. Please be advised that running scapy which perhaps depends on tcpdump on Raspberry Pi might be CPU exhaustive. Please take a look at the following snippet:

import socket
import time
import sys
from scapy.all import *


def send_hs_command(address, port, cmd):
    data = b""
    tcp_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    try:
        tcp_sock.connect((address, port))
        tcp_sock.send(encrypt(cmd))
        data = tcp_sock.recv(2048)
    except socket.error:
        print(time.asctime( time.localtime(time.time()) ), "Socket closed.", file=sys.stderr)
    finally:
        tcp_sock.close()
    print(data)
    return data


def get_ip_from_mac():
    # Match ARP requests
    packet_list = sniff(filter="arp", count=10) # increase number of arp counts
    for i in packet_list:
        # Show all ARP requests
        # print(i[Ether].src, "is broadcasting IP", i[ARP].psrc)
        if (i[ARP].hwsrc == '00:0c:29:b6:f4:be'): # target MAC address
            return (True, i[ARP].psrc)
    return (False, '')


def main():
    result = get_ip_from_mac()
    if result[0] == True:
        print("Succeeded to reach server")
        send_hs_command(result[1], 22, b'{"emeter":{"get_realtime":{}}}')
    else:
        # logic to retry or graciously fail
        print("Failed to reach server")


if __name__== "__main__":
    main()


来源:https://stackoverflow.com/questions/56003031/how-to-incorporate-the-ip-address-of-a-device-into-a-python-script-if-the-addres

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!