mad madane
mad madane

Reputation: 85

Remove leading zeros from IP Address with C#

I have an IP like this "127.000.000.001" how can I remove the leading zeros to get this "127.0.0.1"? For now i use regex like this

Regex.Replace("127.000.000.001", "0*([0-9]+)", "${1}")

Is there any other way to achieve this result without using regex?

I use visual C# 3.0 for this code

Upvotes: 7

Views: 3850

Answers (5)

Amit
Amit

Reputation: 21

don't need regex to do that, you can do something like this.

IPAddress IP = IPAddress.Parse("127.000.000.001");
IP.ToString()

Upvotes: 0

akshay jain
akshay jain

Reputation: 1

you can use below logic writien in C.

#include<stdio.h>
#include<string.h>
#include <arpa/inet.h>

int main(int argc, char** argv)
{
    int inlen=strlen(argv[1])+1, cnt=0, dstcnt=0;
    char dststr[INET_ADDRSTRLEN]="";

    if(argc<2)
    {
        printf("usage: ipvalidator [ip]\n");
        return 0;
    }

    for(cnt=0; cnt<inlen; cnt++)
    {
        if(argv[1][cnt]=='\0')
        {
            break;
        }
        
        if( (argv[1][cnt]=='0') && (argv[1][cnt+1] == '0') &&
            ((cnt==0) ||(argv[1][cnt-1] == '.') || (argv[1][cnt-1] == '0')) )
        {
            continue;
        }
        
        if( (argv[1][cnt]=='0') && (argv[1][cnt+1] >= '1') && 
            (argv[1][cnt+1] <= '9') && 
            ((cnt==0) || (argv[1][cnt-1] == '.') || (argv[1][cnt-1] == '0')) )
        {
            continue;
        }

        dststr[dstcnt++] = argv[1][cnt];

    }
    dststr[dstcnt++] = '\0';

    printf("New IP String: %s\n",dststr);
    return dstcnt;
}

Upvotes: -2

scottheckel
scottheckel

Reputation: 9244

As stated by @Brent, IPAddress.TryParse treats leading zeros as octal and will result in a bad answer. One way of fixing this issue is to use a RegEx.Replace to do the replacement. I personally like this one that looks for a 0 followed by any amount of numbers.

Regex.Replace("010.001.100.001", "0*([0-9]+)", "${1}")

It will return 10.1.100.1. This will work only if the entire text is an IP Address.

Upvotes: 2

Brent
Brent

Reputation: 141

The IP Address object will treat a leading zero as octal, so it should not be used to remove the leading zeros as it will not handle 192.168.090.009.

http://social.msdn.microsoft.com/Forums/en-US/netfxbcl/thread/21510004-b719-410e-bbc5-a022c40a8369

Upvotes: 14

Cody Gray
Cody Gray

Reputation: 244732

Yes, there's a much better way than using regular expressions for this.

Instead, try the System.Net.IpAddress class.

There is a ToString() method that will return a human-readable version of the IP address in its standard notation. This is probably what you want here.

Upvotes: 10

Related Questions