[英]My socket program doesn't print the output
Just getting started with socket programming, I have created the below code and expecting to print some byte data, but it isn't doing that. 刚开始使用套接字编程,我已经创建了以下代码,并希望打印一些字节数据,但它没有这样做。
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)
It just sits and does nothing. 它只是坐着,什么也不做。
any directions would be appreciated. 任何方向将不胜感激。
You should have a server where the requests can be sent by the client to print the data 您应该有一台服务器,客户端可以在其中发送请求以打印数据
Below is a sample program where you can send message from client and receive the output that was modified by the server 下面是一个示例程序,您可以在其中从客户端发送消息并接收服务器修改的输出
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
OUTPUT 输出值
SIVABALANs-MBP:Desktop siva$ python client.py
Input lowercase sentence:siva
SIVA
SIVABALANs-MBP:Desktop siva$
EDIT: 编辑:
Maybe you can try this code 也许您可以尝试此代码
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"
I could not test the code in my system as AF_PACKET does not work in mac. 由于AF_PACKET在Mac中不起作用,因此无法在系统中测试代码。 Try and let me know if in case it works. 尝试并让我知道是否可以使用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.