import socket
import binascii

def action(host, port):
    # CoDeSyS little endian query
    lile_query = binascii.unhexlify("bbbb0100000001")
    # CoDeSyS big endian query
    bige_query = binascii.unhexlify("bbbb0100000101")
    
    # Create a socket
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    
    try:
        # Connect to the remote host
        sock.connect((host, port))
        
        # Send the little endian query
        sock.send(lile_query)
        
        # Receive the response
        response = sock.recv(1024)
        
        # If there was no response, try the big endian query
        if not response:
            sock.send(bige_query)
            response = sock.recv(1024)
        
        # Check if the response starts with 0xbb
        if response and response[0] == 0xbb:
            # Extract the null-terminated strings (OS Name, OS Type, Product Type)
            os_name_end = response.find(b'\x00', 64)
            os_name = response[64:os_name_end].decode()
            
            os_type_end = response.find(b'\x00', 96)
            os_type = response[96:os_type_end].decode()
            
            product_type_end = response.find(b'\x00', 128)
            product_type = response[128:product_type_end].decode()
            
            # Close the socket
            sock.close()
            
            output = {
                "OS Name": os_name,
                "Product Type": product_type,
                "Device IP":host,
                "Port":port
            }
            return output
        
    except Exception as e:
        print(f"Error: {e}")
        return None

def get_info(ip,port):
	return(action(ip,port))