title: Modbus TCP with Python
body: <p>I am trying to communicate with Modbus via TCP. I want to use this type of code without a library. </p>
  
  <p>The code is run like this :</p>
  
  <pre><code> sudo python3 modbus_master.py
  </code></pre>
  
  <p>When I run the program with this code then I see my Modbus connection defined in Wireshark. I am also using slave Modbus programs (more than one) but there is no connection with my master. </p>
  
  <p><strong>What am I doing wrong in the following code?</strong></p>
  
  <pre><code>#!/usr/bin/python3           
  # This is client.py file
  
  import socket
  import struct
  import time
  
  # Create a TCP/IP socket
  TCP_IP = '192.168.0.107'
  TCP_PORT = 502
  BUFFER_SIZE = 39
  sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  sock.connect((TCP_IP, TCP_PORT))
  
  try:
  
      unitId = 16
      functionCode = 5
      print("\n,Switching plug on")
      coilId = 1
      req = struct.pack('12B', 0x00, 0x00, 0x00, 0x00, 0x00, 0x06, int(unitId), int(functionCode), 0x00, int(coilId),
                        0xff,
                        0x00)
      sock.send(req)
      print("TX: (%s)" % req)
  
  
      time.sleep(2)
  
  finally:
      print('\nCLOSING SOCKET')
      sock.close()
  </code></pre>