0

I am trying to get 4 integers from an IP-address. For example, 12.34.56.78. A = 12, b = 34, c = 56, and d = 78. Here is my code:

#include <stdio.h>
#include <stdlib.h>
        
int main()
{
    char ADDRESS[100];
        
    printf("Enter IP: ");
    scanf("%s", ADDRESS);
    return 0;
}

How would I be able to do this?

Steve Friedl
  • 3,929
  • 1
  • 23
  • 30
  • What should happen if someone enters an IPv6 address? – Dai Apr 29 '21 at 20:28
  • 1
    read about `strtok()`. – Sourav Ghosh Apr 29 '21 at 20:28
  • `ADDRESS` isn't a preprocessor macro, so it should not be in all-caps. – Dai Apr 29 '21 at 20:28
  • possible duplicate of https://stackoverflow.com/questions/9210528/split-string-with-delimiters-in-c - I found this by doing a simple googl search for "c split string" - sou would it have for you … – TheEagle Apr 29 '21 at 20:33
  • Why would you want 4 integers from an IP-address? Why not just parse it into a `struct in_addr`? If you think an IP address consists of 4 integers, you don't understand network addressing. – Cheatah Apr 29 '21 at 21:12
  • @Cheatah Ridiculous comment -- an IPv4 address can be represented as 4 8-bit integers. And perhaps they're not using POSIX networking . – M.M Apr 29 '21 at 21:17
  • 1
    It can also be represented as 8 hexadecimal characters, as a barcode or as a drawing of a moose. That does not mean it is convenient to use such representation format in memory. It will likely result in inconvenient and/or unnecessary stuff. It's almost always better to just treat it as a 32-bit object. – Cheatah Apr 29 '21 at 21:35

2 Answers2

5

try to use good old sscanf().

int A, B, C, D;
sscanf(ADDRESS, "%d.%d.%d.%d", &A, &B, &C, &D);

It may be a good idea to check if sscanf() returned 4 what indicates that all four numbers were correctly parsed.

tstanisl
  • 13,520
  • 2
  • 25
  • 40
0

if you're asked to read it as a string at first , you need to add a condition that it exists 4 points in the string

do { 
count=0;
   for (i=0;i<strlen(address);i++) {
        if (address[i] == '.') 
         count++;
         }
 if (count > 4) {
       printf("Enter IP: ");
scanf("%s", ADDRESS); }
while (!(count <= 4));

secondly using strtok can make everything easy , you have to split your string with the . caracter so it goes with something like this

char *tester;
int counter=0,a,b,c,d;
tester = strtok(address, ".");
while( tester != NULL ) {
  switch (counter)  {
   case 0:
   a=atoi(tester);
   counter++;
   break;
   case 1:
   b=atoi(tester);
   counter++;
   break;
   case 2 :
   c=atoi(tester);
   counter++;
   break;
   case 3:
   d=atoi(tester);
   counter++;
   break; }
  tester= strtok(NULL, ".");
}