我如何通过Python发送除字符串以外的任何东西sock.send() [英] How can I send anything other than strings through Python sock.send()

查看:763
本文介绍了我如何通过Python发送除字符串以外的任何东西sock.send()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对Python编程非常新颖,但是出于必要,我必须快速地将一些东西拼凑在一起。

I'm very very new to programming in Python, but out of necessity I had to hack something together very quick.

我试图发送一些数据UDP和我有一切工作,除了当我做socket.send()时,我必须以字符串形式输入数据。这是我的程序,所以你可以看到我在做什么:

I am trying to send some data over UDP, and I have everything working except for the fact that when I do socket.send(), I have to enter the data in string form. Here is my program so you can see what I am doing:

import socket


IPADDR = '8.4.2.1'
PORTNUM = 10000

s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, 0)

s.connect((IPADDR, PORTNUM))

s.send('test string'.encode('hex'))

s.close()

例如,我可以如何获取它,以便我可以像s.send(ff:23:25:a1)那样以十六进制的方式执行某些操作,所以当我在Wireshark中查看数据包的数据部分时,我看到了ff:23:25:a1

How could I get it so that I can do something in hexadecimal like s.send(ff:23:25:a1) for example, so that when I look at the data portion of the packet in Wireshark, I see ff:23:25:a1

推荐答案

你使用Python 2.7还是3.2?

Are you using Python 2.7 or 3.2?

在3.2中你可以这样做:

In 3.2 you could do:

data = bytes.fromhex('01AF23')
s.send(data)



<那么数据将等于:

Data would then be equal to:

b'\x01\xAF\x23'

在2.7中,可以用以下方法完成:

In 2.7 the same could be accomplished with:

data = '01AF23'.decode('hex')

这篇关于我如何通过Python发送除字符串以外的任何东西sock.send()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆