了解并创建Python协议

时间:2017-02-10 08:53:13

标签: c# python protocols

我有关于如何使用TCP / IP二进制流API的文档。附图显示了协议。我在C#中有一个这方面的工作示例。我想用python来做这件事,因为我不知道c#或windows。

我假设我会使用python套接字,然后我必须发送API消息,有效负载查看此文档。

你能指出我正确的方向来实现python吗?

如何设置它以确认这是验证消息,0x21并压缩数据等?

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((HOST, PORT))
s.sendall(u"{'username':'username', 'password':'password'}".encode('utf8'))

Protocol doc enter image description here enter image description here enter image description here

2 个答案:

答案 0 :(得分:2)

在OSI模型中,至少在第5层(会话)上位于第4层(传输,TCP / IP,...)之上。有一些会话层协议的实现示例,例如httpftp,...在http://github.com/python-git/python/blob/master/Lib/ftplib.pyhttp://github.com/python-git/python/blob/master/Lib/httplib.py

因为你的协议包含标题可能 http 是更好的例子

使用 http 协议中的TCP / IP API参见 http://www.stackoverflow.com/questions/8315209/sending-http-headers-with-python

import socket

sock = socket.socket()
sock.bind(('', 8080))
sock.listen(5)
client, adress = sock.accept()

print "Incoming:", adress
print client.recv(1024)
print

client.send('HTTP/1.0 200 OK\r\n')
client.send("Content-Type: text/html\r\n\r\n")
client.send('<html><body><h1>Hello World</body></html>')
client.close()

print "Answering ..."
print "Finished."

sock.close()

据我所知,你完全跳过代码中的标题(版本,序列,类型,编码......),你必须在发送框架时添加它们

所以试试

self.socket.send(...headers...)
self.socket.send(u"{'username':'username', 'password':'password'}".encode('utf8')) // has to be send as JSON ???

另见http://www.stackoverflow.com/questions/22083359/send-tetx-http-over-python-socket

ftp示例(无标题...)

    # Internal: send one line to the server, appending CRLF
    def putline(self, line):
    line = line + CRLF
    if self.debugging > 1: print '*put*', self.sanitize(line)
    self.sock.sendall(line)

另见 scapy

答案 1 :(得分:0)

我尝试使用tcp协议一次。您可以在所有请求中发送授权值(用户名,密码)。其他数据包含exp({&#39;用户名&#39;:&#39;用户名&#39;,&#39;密码&#39;:& #39;密码&#39;,&#39;数据&#39;:&#39;价值&#39;})。这样就没有任何当前的数据标准。许多tcp客户端发送这样的数据#A#:username; password; #D:value \ n(A -authorization,D -data),example