python - 如何以普通字符显示ip

标签 python special-characters ip-address

我的脚本有问题。为了进行测试,我想打印一个 src 和 dst ip 地址,但显示的字符很特殊,经过多次研究后我仍然不明白为什么...... 我确定这是一个简单的问题,但我没有明白...

这是输出:

problem

这是我的脚本:

import pcapy
import dpkt
from threading import Thread
import re
import binascii

liste=[]
listip=[]
piece_request_handshake = re.compile('13426974546f7272656e742070726f746f636f6c(?P<reserved>\w{8})(?P<info_hash>\w{20})(?P<peer_id>\w{20})')
piece_request_tcpclose = re.compile('(?P<start>\w{12})5011')


class PieceRequestSniffer(Thread):
    def __init__(self, dev='eth0'):
        Thread.__init__(self)

        self.expr = 'udp or tcp'

        self.maxlen = 65535  # max size of packet to capture
        self.promiscuous = 1  # promiscuous mode?
        self.read_timeout = 100  # in milliseconds
        self.max_pkts = -1  # number of packets to capture; -1 => no limit

        self.active = True
        self.p = pcapy.open_live(dev, self.maxlen, self.promiscuous, self.read_timeout)
        self.p.setfilter(self.expr)

    @staticmethod
    def cb(hdr, data):

        eth = dpkt.ethernet.Ethernet(str(data))
        ip = eth.data

            #Select Ipv4 packets because of problem with the .p in Ipv6
        if eth.type == dpkt.ethernet.ETH_TYPE_IP6:
            return
        else:

            #Select only TCP protocols
            if ip.p == dpkt.ip.IP_PROTO_TCP:
                tcp = ip.data

                try:
                    #Return hexadecimal representation
                    hex_data = binascii.hexlify(tcp.data)
                except:
                    return

                fin_flag = ( tcp.flags & dpkt.tcp.TH_FIN ) != 0
                if fin_flag:
                    print " -------------------FIN filtered-------------------"
                    src_ip = ip.src
                    dst_ip = ip.dst
                    #listip.append(theip)
                    print "\n"
                    print "src_ip %s  %s dst_ip %s" % (src_ip,"\n", dst_ip)
                    #for element in zip(str(listip),str(thedata)):
                        #print(element)

    def stop(self):
        #logging.info('Piece Request Sniffer stopped...')
        self.active = False

    def run(self):
        while self.active:
            self.p.dispatch(0, PieceRequestSniffer.cb)


sniffer = PieceRequestSniffer()
sniffer.start()

最佳答案

首先,导入socket,然后使用:

src_ip = socket.inet_ntoa(ip.src)
dst_ip = socket.inet_ntoa(ip.dst)

关于python - 如何以普通字符显示ip,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29917123/

相关文章:

python - 使用opencv阈值图像以获得与imagemagick相同的结果

unicode - 使用特殊字符的编程语言

c - 如何从文件中读取带有特殊字符的浮点型数字

python - 使用 memory_profiler 分析 Flask 应用程序中的行

python - Windows 7 上的 Conda 更新因 yaml 导入错误而失败

python - 重用执行标志检查的方法中的代码

iphone - 编写应用程序网络浏览器以访问 ip 地址

linux - 意外创建了带有句点的目录。特点

c++ - 初始化 asio::ip::address_v6() 的最快方法?

docker - 在Docker 1.10中无法解析主机名