RegEx匹配收到的邮件头上的IP:

时间:2014-02-18 14:59:50

标签: regex

我尝试调整一个RegEx,它只返回发件人IP地址:

http://regexr.com?38atl

这是我构建的RegEx,但无法完成:

(?<=\bReceived: from .*\[)(?:\d{1,3}\.){3}\d{1,3}

(?<=\bReceived: from )(.*\[)(?:\d{1,3}\.){3}\d{1,3}

所以它应该只匹配这个(在开头的行上:Received:from)

127.0.0.1
127.0.0.1
21.22.23.24

这是我搜索的邮件标题示例:

To: a@domain.de
Return-Path: <t@domain.de>
X-Original-To: a@domain.de
Delivered-To: c@domain.tld
Received: from localhost (localhost [127.0.0.1])
        by mail1.domain.tld (Postfix) with ESMTP id 3fT3TR72zNz8m8
        for <a@domain.de>; Tue, 18 Feb 2014 14:54:35 +0100 (CET)
X-Virus-Scanned: Debian amavisd-new at mail1.domain.tld
X-Spam-Flag: YES
X-Spam-Score: 5.773
X-Spam-Level: *****
X-Spam-Status: Yes, score=5.773 tagged_above=1 required=4.5
        tests=[BAYES_05=-0.5, MISSING_MID=0.497, RCVD_IN_PBL=3.335,
        RCVD_IN_RP_RNBL=1.31, RDNS_DYNAMIC=0.982, TO_NO_BRKTS_DYNIP=0.139,
        T_RCVD_IN_SEMBLACK=0.01] autolearn=no
Received: from mail1.domain.tld ([127.0.0.1])
        by localhost (mail1.domain.tld [127.0.0.1]) (amavisd-new, port 10024)
        with ESMTP id lDJqiZjBn2t4 for <a@domain.de>;
        Tue, 18 Feb 2014 14:54:34 +0100 (CET)
Received: from mail.domain.tld (pAAAAAAAA.dip0.t-ipconnect.de [21.22.23.24])
        by mail1.domain.tld (Postfix) with SMTP id 3fT3TQ4Nwgz8m5
        for <a@domain.de>; Tue, 18 Feb 2014 14:54:34 +0100 (CET)
Date: Tue, 18 Feb 2014 15:02:11 +0100
Sender: "From" <t@domain.de>
From: "From" <t@domain.de>
Subject: Subbbb (192.168.123.123)
Reply-To: t@domain.de
MIME-Version: 1.0
Content-type: text/plain; charset=UTF-8
Message-Id: <3fT3TR72zNz8m8@mail1.domain.tld>

3 个答案:

答案 0 :(得分:4)

试试这个表达式:

Received: +from[^\n]*?\[([0-9\.]+)\]

编辑:

对于PHP脚本尝试类似这样的事情(其中$ emailHeader包含您要搜索的数据):

$regex = '/Received: +from[^\\n]*?\\[([0-9\\.]+)\\]/s';
if  (preg_match_all($regex, $emailHeader, $matches_out)) {
  print_r($matches_out);
} else {
  print('Sender IP not found');
}

答案 1 :(得分:0)

明星中的&lt; =看起来很有趣,但除此之外似乎工作正常:

(?:\bReceived: from .*\[)((\d{1,3}\.){3}\d{1,3})(?:]\))

答案 2 :(得分:0)

我相信你所寻找的是:

(?:\bReceived: from .*?\[)(?<ip>(?:\d{1,3}\.){3}\d{1,3})

匹配的IP地址将位于名为“ip”的捕获组中。