cpound
cpound

Reputation: 85

Need help to get IP from strings in c#

So I'm working on a little side project in c# and want to read a long text file and when it encounters the line "X-Originating-IP: [192.168.1.1]" I would like to grab the IP and display to console just the recognized IP #, so just 192.168.1.1 etc. I am having trouble understanding regex. Anyone who could get me started is much appreciated. What I have so far is below.

namespace x.Originating.Ip
{
    class Program
    {
        static void Main(string[] args)
        {
            int counter = 0;
            string line;
            System.IO.StreamReader file =
                new System.IO.StreamReader("C:\\example.txt");

            while ((line = file.ReadLine()) != null)
            { 
                if (line.Contains("X-Originating-IP: "))
                Console.WriteLine(line);
                counter++;
            }

            file.Close();
            Console.ReadLine();
        }
    }
}

Upvotes: 3

Views: 3522

Answers (6)

Raipa Sanaat
Raipa Sanaat

Reputation: 11

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            System.Net.WebClient webclient = new System.Net.WebClient();
            string ip = webclient.DownloadString("http://whatismyip.org/");
            Regex reg = new Regex("((2[0-4]\\d|25[0-5]|[01]?\\d\\d?)\\.){3}(2[0-4]\\d|25[0-5]|[01]?\\d\\d?)");
            if (reg.Match(ip).Success)
            {
                Console.WriteLine(reg.Match(ip).ToString ());
                Console.WriteLine("Success");
            }
        //    Console.Write (ip);
            Console.ReadLine();
        }
    }
}

Upvotes: 1

Mitch
Mitch

Reputation: 22301

Rather than doing a regex, it looks like you are parsing a MIME email, consider LumiSoft.Net.MIME which lets you access the headers with a defined API.

Alternatively, use the built in IPAddress.Parse class, which supports both IPv4 and IPv6:

const string x_orig_ip = "X-Originating-IP:";
string header = "X-Originating-IP: [10.24.36.17]";    

header = header.Trim();
if (header.StartsWith(x_orig_ip, StringComparison.OrdinalIgnoreCase))
{
    string sIpAddress = header.Substring(x_orig_ip.Length, header.Length - x_orig_ip.Length)
        .Trim(new char[] { ' ', '\t', '[', ']' });
    var ipAddress = System.Net.IPAddress.Parse(sIpAddress);
    // do something with IP address.
  return ipAddress.ToString();
}

Upvotes: 0

falsetru
falsetru

Reputation: 369394

You don't need to use regular expression:

if (line.Contains("X-Originating-IP: ")) {
    string ip = line.Split(':')[1].Trim(new char[] {'[', ']', ' '});
    Console.WriteLine(ip);
}

Upvotes: 5

DareDevil
DareDevil

Reputation: 5349

Try this example:

//Add this namespace
using System.Text.RegularExpressions;

String input = @"X-Originating-IP: [192.168.1.1]";
Regex IPAd = new Regex(@"\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b");
MatchCollection MatchResult = IPAd.Matches(input);
Console.WriteLine(MatchResult[0]); 

Upvotes: 7

JNYRanger
JNYRanger

Reputation: 7097

The following regular expression should get you what you want:

(?<=X-Originating-IP: +)((2[0-4]\d|25[0-5]|[01]?\d\d?)\.){3}(2[0-4]\d|25[0-5]|[01]?\d\d?)

This uses a positive lookbehind to assert that "X-Originating-IP: " exists followed by an IPv4 address. Only the IP address will be captured by the match.

Upvotes: 0

user3221822
user3221822

Reputation:

I'm not sure but I suppose your text file contains one IP address each row, now your codes can be simplified like this below:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Text.RegularExpressions;


namespace x.Originating.Ip
{
    class Program
    {
        static void Main(string[] args)
        {
            string[] lines = System.IO.File.ReadAllLines("Your path & filename.extension");
            Regex reg = new Regex("((2[0-4]\\d|25[0-5]|[01]?\\d\\d?)\\.){3}(2[0-4]\\d|25[0-5]|[01]?\\d\\d?)");
            for (int i = 0; i < lines.Length; ++i)
            {
                if (reg.Match(lines[i]).Success)
                {
                    //Do what you want........
                }
            }
        }
    }
}

Upvotes: 0

Related Questions