import socket
import struct
from ip_packet import IPPacket


class IPLayer:
    rc = None
    ss = None
    src = None
    
    def __init__(self):
        self.rc = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_TCP)
        self.ss = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_RAW)
        self.ss.setsockopt(socket.IPPROTO_IP, socket.IP_HDRINCL, True)
        self.src = IPLayer.get_ip_address()


    def send(self, dst, data):
        packet = IPPacket()
        print("IP packet: ", data)
        packet.src = socket.inet_aton(self.src)
        packet.dst = socket.inet_aton(dst)
        packet.data = data
        foo = packet.to_hex_string()
        print(len(foo), foo)
        self.ss.sendto(foo, (dst, 0))
        return
        # self.ss.sendto(packet.to_hex_string(), (dst, 0))

    



    @staticmethod
    def get_ip_address():
        s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        s.connect(("8.8.8.8", 80))
        return s.getsockname()[0]
    

def main():
    ip_layer = IPLayer()
    print(ip_layer.get_ip_address())


if __name__ == "__main__":
    main()
