-5

I've written a program to geolocate a senders generic location, however I'm having problems extracting the IP address from my string for example:

   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 "";
        }

// I've captured the complete EMAIL'S MIME data to a string (txtEmail) // Now I search the string ...

  //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;

Any Ideas?

2
  • 5
    ideas.Any() == false ... Mar 14, 2013 at 14:08
  • 1
    What do you get in data while debugging?
    – Tawnos
    Mar 14, 2013 at 14:12

2 Answers 2

1

I would suggest a regular expression

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

8
  • I guess I forgot mention that the text is contained with a multiline text box. So I' searching the text ("txtEmail) for the specific line.
    – DevNULL
    Mar 14, 2013 at 14:31
  • you don't need to search the text for that line. Just pass the whole MIME headers of the e-mail as input to the regular expression. It should do the rest. That's why the RegexOptions.Multiline and RegexOptions.Singleline were ingluded. Mar 14, 2013 at 14:33
  • @DevNULL, it looks like my link war broken earlier. I've updated with a working link: rextester.com/BOOWV76810 Please see that code.. Mar 14, 2013 at 14:36
  • I understand, and your're 100% right, but in this case the entire MIME is needed in this case. Pretty critical actually. (Needs to be printed for verification in court).
    – DevNULL
    Mar 14, 2013 at 14:36
  • can you post an example of the entire MIME? That's what I'm saying. That you can just use the entire MIME, just pass it to the regex and it will extract the IP for you. Mar 14, 2013 at 14:38
1

Similar to Miky but making use of positive lookahead/behind so we only select the IP address.

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.