gpt4 book ai didi

python - 我的套接字程序不打印输出

转载 作者:行者123 更新时间:2023-12-03 12:08:49 26 4
gpt4 key购买 nike

刚开始使用套接字编程,我已经创建了以下代码,并希望打印一些字节数据,但它没有这样做。

import socket

def create_socket():
s = socket.socket(socket.AF_PACKET, socket.SOCK_RAW, socket.ntohl(3))

while True:
rdata, address = s.recvfrom(65535)
print(rdata)

它只是坐着,什么也不做。

任何方向将不胜感激。

最佳答案

您应该有一台服务器,客户端可以在其中发送请求以打印数据

下面是一个示例程序,您可以在其中从客户端发送消息并接收服务器修改的输出

SERVER.PY

from socket import *
serverPort = 12048
serverSocket = socket(AF_INET, SOCK_DGRAM)
serverSocket.bind(('', serverPort))
print 'The server is ready to receive'
while 1:
message,clientAddress = serverSocket.recvfrom(2048)
modifiedMessage = message.upper()
serverSocket.sendto(modifiedMessage, clientAddress)

CLIENT.PY
from socket import *
serverName = '127.0.0.1'
serverPort = 12048
clientSocket = socket(AF_INET,SOCK_DGRAM)
message = raw_input('Input lowercase sentence:')
clientSocket.sendto(message,(serverName, serverPort))
modifiedMessage, serverAddress =clientSocket.recvfrom(2048)
print modifiedMessage

输出
SIVABALANs-MBP:Desktop siva$ python client.py 
Input lowercase sentence:siva
SIVA
SIVABALANs-MBP:Desktop siva$

编辑:

也许你可以试试这个代码
import socket
import struct
import binascii

rawSocket = socket.socket(socket.AF_PACKET,
socket.SOCK_RAW,
socket.htons(0x0003))

while True:

packet = rawSocket.recvfrom(2048)
ethhdr = packet[0][0:14]
eth = struct.unpack("!6s6s2s", ethhdr)

arphdr = packet[0][14:42]
arp = struct.unpack("2s2s1s1s2s6s4s6s4s", arphdr)
# skip non-ARP packets
ethtype = eth[2]
if ethtype != '\x08\x06': continue

print "---------------- ETHERNET_FRAME ----------------"
print "Dest MAC: ", binascii.hexlify(eth[0])
print "Source MAC: ", binascii.hexlify(eth[1])
print "Type: ", binascii.hexlify(ethtype)
print "----------------- ARP_HEADER -------------------"
print "Hardware type: ", binascii.hexlify(arp[0])
print "Protocol type: ", binascii.hexlify(arp[1])
print "Hardware size: ", binascii.hexlify(arp[2])
print "Protocol size: ", binascii.hexlify(arp[3])
print "Opcode: ", binascii.hexlify(arp[4])
print "Source MAC: ", binascii.hexlify(arp[5])
print "Source IP: ", socket.inet_ntoa(arp[6])
print "Dest MAC: ", binascii.hexlify(arp[7])
print "Dest IP: ", socket.inet_ntoa(arp[8])
print "------------------------------------------------\n"

我无法在系统中测试代码,因为AF_PACKET在Mac中不起作用。尝试让我知道是否可以正常使用。

关于python - 我的套接字程序不打印输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48020839/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com