Discovering data type of incoming socket data in python
Question: There are couple of devices which are sending socket data over _TCP/IP_ to
socket server. Some of the devices are sending data as _Binary encoded
Hexadecimal string_ , others are _ASCII string_.

Eg.;

If device sending data in _ASCII string_ type, script is begin to process
immediately without any conversion.

If device sending _Binary encoded HEX string_ , script should has to convert
_Binary encoded Hex string_ into _Hex string_ first with;

    
    
    data = binascii.hexlify(data)
    

There are two scripts running for different data types for that simple single
line. But, I think this could be done in one script if script be aware of the
incoming data type. Is there a way to discover type of the incoming socket
data in Python?


Answer: If you can you should make the sending devices signal what data they are
sending eg by using different TCP ports or prepending each message with an
`"h"` for hex or an `"a"` for ascii - possibly even use an established
protocol like [XML-RPC](https://docs.python.org/3/library/xmlrpc.html)

Actually you can only be sure in _some_ cases as all hex-encoded strings are
valid ascii and some ascii-strings are valid hex like `"CAFE"`. You can make
sure you can decode a string as hex with

    
    
    import string
    def is_possibly_hex(s):
        return all(c in string.hexdigits for c in s)
    

or

    
    
    import binascii
    def is_possibly_hex(s):
        try:
            binascii.unhexlify(s)
        except binascii.Error:
            return False
        return True
    

