Discovering data type of incoming socket data in python
<p>There are couple of devices which are sending socket data over <em>TCP/IP</em> to socket server. Some of the devices are sending data as <em>Binary encoded Hexadecimal string</em>, others are <em>ASCII string</em>.</p>

<p>Eg.;</p>

<p>If device sending data in <em>ASCII string</em> type, script is begin to process immediately without any conversion.</p>

<p>If device sending <em>Binary encoded HEX string</em>, script should has to convert <em>Binary encoded Hex string</em> into <em>Hex string</em> first with;</p>

<pre><code>data = binascii.hexlify(data)
</code></pre>

<p>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?</p>

<p>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 <code>"h"</code> for hex or an <code>"a"</code> for ascii - possibly even use an established protocol like <a href="https://docs.python.org/3/library/xmlrpc.html" rel="nofollow">XML-RPC</a></p>

<p>Actually you can only be sure in <em>some</em> cases as all hex-encoded strings are valid ascii and some ascii-strings are valid hex like <code>"CAFE"</code>.
You can make sure you can decode a string as hex with</p>

<pre><code>import string
def is_possibly_hex(s):
    return all(c in string.hexdigits for c in s)
</code></pre>

<p>or</p>

<pre><code>import binascii
def is_possibly_hex(s):
    try:
        binascii.unhexlify(s)
    except binascii.Error:
        return False
    return True
</code></pre>

python sockets types