23

For example, I have this string: 10.10.10.10/16

and I want to remove the mask from that IP and get: 10.10.10.10

How could this be done?

INDRAJITH EKANAYAKE
  • 3,894
  • 11
  • 41
  • 63
Itzik984
  • 15,968
  • 28
  • 69
  • 107

6 Answers6

34

Here is how you would do it in C++ (the question was tagged as C++ when I answered):

#include <string>
#include <iostream>

std::string process(std::string const& s)
{
    std::string::size_type pos = s.find('/');
    if (pos != std::string::npos)
    {
        return s.substr(0, pos);
    }
    else
    {
        return s;
    }
}

int main(){

    std::string s = process("10.10.10.10/16");
    std::cout << s;
}
Andy Prowl
  • 124,023
  • 23
  • 387
  • 451
18

Just put a 0 at the place of the slash

#include <string.h> /* for strchr() */

char address[] = "10.10.10.10/10";
char *p = strchr(address, '/');
if (!p)
{
    /* deal with error: / not present" */
    ;
}
else
{
   *p = 0;
}

I don't know if this works in C++

Simson
  • 3,373
  • 2
  • 24
  • 38
pmg
  • 106,608
  • 13
  • 126
  • 198
  • 8
    wasted memory! all 3 bytes of it! – 75inchpianist Feb 21 '13 at 15:56
  • 1
    @75inchpianist What do you mean by that? Where is the memory "wasted" and how? –  Feb 21 '13 at 16:34
  • Shouldn't this be `*p = '\0';` – squareborg Feb 25 '15 at 17:03
  • 3
    @Shutupsquare: except in source form, `'\0'` and `0` are absolutely identical. The first is a literal character: it has type `int` and value `0`; the second is a literal integer: it has type `int` and value `0`. *Things may be different in C++. I don't know that language.* – pmg Feb 25 '15 at 19:13
3
char* pos = strstr(IP,"/"); //IP: the original string
char [16]newIP;
memcpy(newIP,IP,pos-IP);   //not guarenteed to be safe, check value of pos first
Goldie
  • 122
  • 2
  • 4
  • 17
75inchpianist
  • 4,112
  • 1
  • 21
  • 39
1

Example in C++

#include <iostream>
using namespace std;

int main() 
{
    std::string addrWithMask("10.0.1.11/10");
    std::size_t pos = addrWithMask.find("/");
    std::string addr = addrWithMask.substr(0,pos);
    std::cout << addr << std::endl;
    return 0;
 }
nav
  • 410
  • 6
  • 14
0

Example in

char ipmask[] = "10.10.10.10/16";
char ip[sizeof(ipmask)];
char *slash;
strcpy(ip, ipmask);
slash = strchr(ip, '/');
if (slash != 0)
    *slash = 0;
Olaf Dietsche
  • 72,253
  • 8
  • 102
  • 198
0

I see this is in C so I guess your "string" is "char*"?
If so you can have a small function which alternate a string and "cut" it at a specific char:

void cutAtChar(char* str, char c)
{
    //valid parameter
    if (!str) return;

    //find the char you want or the end of the string.
    while (*char != '\0' && *char != c) char++;

    //make that location the end of the string (if it wasn't already).
    *char = '\0';
}
Roee Gavirel
  • 18,955
  • 12
  • 67
  • 94