Connection Reset When Trying to Interact With a Minecraft Server in Python
Question
I have a bit of a problem with attempting to send packets to a Minecraft 1.1 SMP Server.
I have the following file (ServerConnect.py):
import socket
import struct
username = "JackBeePeeBot"
host = "smp.project-vanilla.com:2224"
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(("smp.project-vanilla.com", 2224))
packet = ""
packet += struct.pack(">B", 2)
packet += username
packet += ";"
packet += host
s.send(packet)
print(s.recv(1024))
However, when I try to run this I get the following:
Traceback (most recent call last):
File "ServerConnect.py", line 13, in <module>
print(s.recv(1024))
socket.error: [Errno 104] Connection reset by peer
For anyone unaware of the packet specifications of MineCraft, they can be found here:
I'm trying I send a 'handshake'.
Does anyone know what's going wrong, why and how to fix it?
Any help would be greatly appreciated!
Solution
The protocol documentation says that a "string" is a 2-byte length plus the string bytes in UCS-2 (two characters each). Also, all datatypes are signed.
You should probably try something like this:
import struct
data = {'user':u'JackBeePeeBot','host':u'smp.project-vanilla.com','port':2224}
stringfmt = u'%(user)s;%(host)s:%(port)d'
string = stringfmt % data
structfmt = '>bh'
# 1 byte header, 2 byte *character* (not byte) string length
# and ucs-2/utf-16 BE encoded string
packetbytes = struct.pack(structfmt, 2, len(string))+string.encode('utf-16BE')
packetbytes
is what you should send.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow