struct.error: repeat count given without format specifier

时间:2018-03-23 00:47:52

标签: python struct network-programming

DETAILS

I'm trying to understand a network program that implements the selective repeat (SR) protocol. Here's the process:

  1. Run server.py by specifying a port number, protocol, and window size
  2. Run client.py by specifying a filename, port number, and number of packets

When I run client.py, I receive this error:

Traceback (most recent call last):
File "client.py", line 238, in <module>
cs = pack('IHH' + str(len(data)), 's', seqNum, header, data)
struct.error: repeat count given without format specifier

Here's the block of code that's tripping me up:

while not sendComplete:
    toSend = lastInWindow + 1
    data = GetMessage()
    header = int('0101010101010101', 2)
    cs = pack('IHH' + str(len(data)), 's', seqNum, header, data)
    checksum = CalculateChecksum(cs)

packet = pack('IHH' + str(len(data)) + 's', seqNum, checksum, header, data)
    if toSend < windowSize:
        sendBuffer.append(packet)
        timeoutTimers.append(TIMEOUT)
    else:
        sendBuffer[toSend % windowSize] = packet
        timeoutTimers[toSend % windowSize] = TIMEOUT

TROUBLESHOOTING

I've taken several steps to fix this issue, all of which have failed (obviously), and I'm not sure if I'm getting closer to the light or heading deeper into the woods.

  1. Using struct.pack(fmt=...) as suggested by PyCharm
  2. Per PyCharm's advice, I concatenate the arguments using a +
  3. I run the program again and receive a TypeError: must be str, not int error, which I attempt to fix by implementing str(seqNum), str(header), etc.
  4. Finally, I get a TypeError: pack() takes no keyword arguments response and throw in the towel.

I'd really appreciate it if someone could explain what's going on here and how I can get this program up and running.

1 个答案:

答案 0 :(得分:0)

问题是您在pack格式功能上输入了拼写错误,而不是(&#39;,&#39;而不是&#39; +&#39;):

pack('IHH' + str(len(data)), 's', seqNum, header, data)

它应该是:

pack('IHH' + str(len(data)) + 's', seqNum, header, data)

这是因为每次字节格式都有数字时,它会重复下一个字符数次。因此4h将成为hhhh。错误的行以数字结束(例如:&#34; IHH6&#34;),因此它不知道要重复的内容。

此外,您正在打包4&#34;事情&#34;,您应该为pack函数添加另一个参数:

pack('IHH' + str(len(data)) + 's', seqNum, header, data, missing_var)