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

时间:2017-12-29 10:07:26

标签: python python-3.x sockets networking

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

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)

它只是坐着而什么都不做。

任何方向将不胜感激。

1 个答案:

答案 0 :(得分:0)

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

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

<强> 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中不起作用。如果有效,请试着告诉我。