在c#中捕获电子邮件的IP地址

本文关键字:IP 地址 电子邮件 | 更新日期: 2023-09-27 18:03:59

我写了一个程序来定位发件人的一般位置,但是我有问题从我的字符串中提取IP地址,例如:

   public static string getBetween(string strSource, string strStart, string strEnd)
    {
        int Start, End;
        if (strSource.Contains(strStart) && strSource.Contains(strEnd))
        {
            Start = strSource.IndexOf(strStart, 0) + strStart.Length;
            End = strSource.IndexOf(strEnd, Start);
            return strSource.Substring(Start, End - Start);
        }
        else
        {
            return "";
        }

//我已经捕获了完整的电子邮件的MIME数据到一个字符串(txtEmail)//现在我搜索字符串…

  //THIS IS MY PROBLEM. this is always different. 
  // I need to capture only the IP address between the brackets
  string findIP = "X-Originating-IP: [XXX.XXX.XXX.XXX]"; 
  string data = getBetween(findIP, "[", "]");
  txtCustomIPAddress.Text = data;

任何想法?

在c#中捕获电子邮件的IP地址

我建议使用正则表达式

Regex rex = new Regex("X-Originating-IP'':''s*''[(.*)'']", RegexOptions.Multiline|RegexOptions.Singleline);
string ipAddrText = string.Empty;
Match m = rex.Match(headersText);
if (m.Success){
    ipAddrText = m.Groups[1].Value;
}
// ipAddrText should contain the extracted IP address here

Working Demo Here

与Miky类似,但使用正向向前看/向后看,因此我们只选择IP地址。

var str = "X-Originating-IP: [XXX.XXX.XXX.XXX]";
var m = Regex.Match(str, @"(?<=X-Originating-IP:' '[).*?(?=])");
var ipStr = m.Success ? m.Value : null;