在python中使用原始套接字发送IP数据包

时间:2018-04-28 15:08:38

标签: python python-2.7 ip raw-sockets

总结我的问题:
我有两个问题:

  1. 我无法发送IP_PACKET变量
  2. 如何在IP数据包中设置标志? (发送)
  3. 这是我的代码:

    #! /usr/bin/python
    import socket
    import struct
    import sys
    
    
    def Create_SOCKET():
            global ST
            try:
                    ST = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_RAW)
            except socket.error as MSG:
                    print "[ERROR] Socket creation error:\n", MSG
                    sys.exit()
    
    
    def IP_HEADER(Source_IP, Destination_IP):
            global IP_PACKET
    
            #Variable validation
            IP_VER = 4
            IP_IHL = 5
            IP_TOS = 0
            IP_TOL = 60
            IP_IDT = 54331
            IP_FLG = 2 # 0x02 DF
            IP_FOS = 0
            IP_TTL = 64
            IP_PROTO = socket.IPPROTO_TCP
            IP_CHECKSUM = 0
    
            IP_IHL_VER = (IP_VER << 4) + IP_IHL
    
            SRC_IP = socket.inet_aton(Source_IP)
            DST_IP = socket.inet_aton(Destination_IP)
    
            IP_PACKET = struct.pack("!BBHHHBBH4s4s", IP_IHL_VER, IP_TOS, IP_TOL, IP_IDT, IP_FOS, IP_TTL, IP_PROTO, IP_CHECKSUM, SRC_IP, DST_IP)
    
    
    
            def Send_PACKET(IFACE):
                    try:
                            Create_SOCKET()
                            ST.bind((IFACE, 0))
                            ST.send(IP_PACKET)
                            print "[SUCESS] Packet was sent."
                    except socket.error as MSG:
                            print "[ERROR] Packet can't send:\n", MSG
                            sys.exit()
    
    
    IP_HEADER(sys.argv[1], sys.argv[2])
    Send_PACKET(sys.argv[3])
    

    Python版本:2.7
    操作系统:Ubuntu 16.04
    谢谢你的帮助。

2 个答案:

答案 0 :(得分:0)

您的范围错误,该函数在其他函数中定义,因此它只在本地可用:

def f1():
    pass

def f2():
    def f3():
        pass 
    f3() # works, local scope visible

f1() # works
f2() # works
try:    
    f3() # does not work, is not known, only inde f2()'s scope known
except NameError as ne:
    print(ne)

输出:

name 'f3' is not defined

要修复您的结构,请IP_HEADER(Source_IP, Destination_IP):返回已构建的IP_PACKET,将其存储到变量中,并将其提供给Send_PACKET(IFACE,data) - 同时也是Send_PACKET(...)

def IP_HEADER(Source_IP, Destination_IP):
    # your code
    return IP_PACKET

def Send_PACKET(IFACE,data):  # unindent 4 spaces so its in normal scope
    # your code, use data instead of IP_PACKET

data = IP_HEADER(sys.argv[1], sys.argv[2])
Send_PACKET(sys.argv[3], data)

答案 1 :(得分:0)

第一个问题的解决方案是:

global IP_PACKET
IP_PACKET =[]

enter image description here