绑定到网络接口后,无法在python中通过套接字发送任何原始数据

时间:2017-02-19 09:48:02

标签: python sockets

我正在尝试通过系统的“eth1”接口发送原始十六进制数据包。我写了下面的内容,当我执行它时没有看到任何错误。

#! /usr/bin/python
import socket

class packet:
     hexstr=""

     def getpacket(self,hexs):
            packet.hexstr=hexs
            return packet.hexstr

# create a socket object
s = socket.socket(socket.AF_PACKET, socket.SOCK_RAW, socket.IPPROTO_IP)

# get local machine name

port = 9999

# bind to the port
s.bind(('eth1', port))

#s.setsockopt(IPPROTO_IP, IP_HDRINCL, 1)

pckt = packet()
data = pckt.getpacket("\x68\x65\x6c\x6c\x6f")

msg_send = s.send(data)
#msg_recv = s.recv(4096)
print msg_send
#print msg_recv

然而,当我在端口9999和接口上使用“tcpdump”时,我运行上面的操作,我看不到任何数据包被捕获。

Output:
# ./net_serv.py
5

Dump:
# tcpdump -s0 -i eth1 port 9999
tcpdump: verbose output suppressed, use -v or -vv for full protocol decode
listening on eth1, link-type EN10MB (Ethernet), capture size 65535 bytes

我做错了什么?

1 个答案:

答案 0 :(得分:1)

终于成功了。以下是我实际代码中的一些重要代码段:

#! /usr/bin/python
# some imports
import socket, sys
from struct import *

#create a raw socket
try:
    s = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_RAW)
except socket.error , msg:
    print 'Socket could not be created. Error Code : ' + str(msg[0]) + ' Message ' + msg[1]
    sys.exit()

# tell kernel not to put in headers, since we are providing it, when using IPPROTO_RAW this is not necessary
s.setsockopt(socket.IPPROTO_IP, socket.IP_HDRINCL, 1)

 packet = '';
 source_ip = '192.168.1.101'# Your IP
 dest_ip = '10.10.29.34' #Your IP or socket.gethostbyname('www.google.com')

#Create your own IP, TCP headers and User Data 
## Some hints for those who are really trying it and are new to socket programming like me, make use of the struct, pack() and unpack() in python. 
packet = ip_header + tcp_header + user_data
s.sendto(packet, (dest_ip , 0 ))