[Webinar] Streamline your web hosting managementRegister Today

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 223
  • Last Modified:

convert a network address into a dottted string.

I want to know how to convert an (int)IP into a standard dotted format string.

I know about inet_ntoa, but I want to do know how to it directly???????

thanks
 
0
cosmicmike
Asked:
cosmicmike
  • 2
1 Solution
 
marcjbCommented:
Start by converting the number to a string.  This can be done with the sprintf function.

#include<stdio.h>

int main()
{
int num = 8989;
char the_num[15];
sprintf(the_num, "%i", num);
return 0;
}

The code above puts the number 8989 into the string the_num.

You could then manipulate this string however you like, including using a function like sprintf again to place '.' where you need.

0
 
jhanceCommented:
marcjb,

This won't always work right as it fails to take into account the machine's byte ordering scheme.

cosmic,

I fail to see your reluctance to do it the right way:

#include "stdio.h"
#include "winsock.h"

int main(int argc, char* argv[])
{
      struct in_addr in;
      in.S_un.S_addr = 0x12345678;


      printf("%s\n", inet_ntoa(in));
      return 0;
}
0
 
cosmicmikeAuthor Commented:
sorry marcjb your solution is not 100%

jhance
ok I have an array of int IP nums and I want to convert them in a for next loop and put the dotted results in a char array !!

0
 
jhanceCommented:
OK, how about this?


#include "stdio.h"
#include "winsock.h"

int main(int argc, char* argv[])
{
      char cIP[16][16];
      int iIP[16] = {0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15};
      int i;

      struct in_addr in;

      for(i=0; i<16; i++){
            in.S_un.S_addr = iIP[i];
            strcpy(cIP[i], inet_ntoa(in));
      }


      for(i=0; i<16; i++){
            printf("0x%x = %s\n", iIP[i], cIP[i]);
      }

      return 0;
}
0

Featured Post

Evaluating UTMs? Here's what you need to know!

Evaluating a UTM appliance and vendor can prove to be an overwhelming exercise.  How can you make sure that you're getting the security that your organization needs without breaking the bank? Check out our UTM Buyer's Guide for more information on what you should be looking for!

  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now