1import socket
2
3HOST = '127.0.0.1' # Standard loopback interface address (localhost)
4PORT = 65432 # Port to listen on (non-privileged ports are > 1023)
5
6with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
7 s.bind((HOST, PORT))
8 s.listen()
9 conn, addr = s.accept()
10 with conn:
11 print('Connected by', addr)
12 while True:
13 data = conn.recv(1024)
14 if not data:
15 break
16 conn.sendall(data)
1 import socket
2 import struct
3 import sys
4
5 # CAN frame packing/unpacking (see `struct can_frame` in <linux/can.h>)
6 can_frame_fmt = "=IB3x8s"
7
8 def build_can_frame(can_id, data):
9 can_dlc = len(data)
10 data = data.ljust(8, b'\x00')
11 return struct.pack(can_frame_fmt, can_id, can_dlc, data)
12
13 def dissect_can_frame(frame):
14 can_id, can_dlc, data = struct.unpack(can_frame_fmt, frame)
15 return (can_id, can_dlc, data[:can_dlc])
16
17 if len(sys.argv) != 2:
18 print('Provide CAN device name (can0, slcan0 etc.)')
19 sys.exit(0)
20
21 # create a raw socket and bind it to the given CAN interface
22 s = socket.socket(socket.AF_CAN, socket.SOCK_RAW, socket.CAN_RAW)
23 s.bind((sys.argv[1],))
24
25 while True:
26 cf, addr = s.recvfrom(16)
27
28 print('Received: can_id=%x, can_dlc=%x, data=%s' % dissect_can_frame(cf))
29
30 try:
31 s.send(cf)
32 except socket.error:
33 print('Error sending CAN frame')
34
35 try:
36 s.send(build_can_frame(0x01, b'\x01\x02\x03'))
37 except socket.error:
38 print('Error sending CAN frame')
39