jeudi 30 juin 2016

Issues changing IP Address from int to string

I am trying to convert an IP address (currently IPv4, but recognizes IPv6) from an int array format to a formatted string. I am working on Ubuntu Linux.

I distinguish between IPv4 and IPv6 addresses, and then try to convert the int array to a string.

This is the code that I'm using:

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

int main(void)
{
    int i;
    unsigned int val32;
    int ma_ip[4];
    char m_ip[4];
    char ipaddr[INET_ADDRSTRLEN], ipv6[INET6_ADDRSTRLEN];
    int no = 0;
    char *token;
    char s3[] = "10.1.35.1";
    /* just example. test only one ip address.. */
    for(i = 0; i < 1; i++)
    {
        char *mm = strstr(s3, ":");
        if( *mm != NULL)
        {
             token = strtok(s3, ":");
             while(token != NULL)
             {
                 token = strtok(NULL, ":");
                 no++;
             }
             if(no >= 2 && no <= 7)
                 printf("nthis is ipv6n");
             else
                 printf("nwrong ipv6n");
         }
         else
         {
             token = strtok(s3, ".");
             while(token != NULL)
             {
                 token = strtok(NULL, ".");
                 no++;
             }
             if(no == 4)
             {
                 printf("nthis is ipv4.n");
                 val32 = inet_addr(s3)
                 ma_ip[i] = val32;
             }
             else
                 printf("nwrong ipv4.n")
         }
         inet_ntop(AF_INET,&ma_ip[0],ipaddr,INET_ADDRSTRLEN);
         printf("nipaddr = %sn", ipaddr);
         strcpy(&m_ip[0], ipaddr);
         printf("nafter strcpy = %sn", m_ip[0]);
    }
}

This output is wrong:

ipaddr = 0.0.0.10

It should actually be:

ipaddr = 10.1.35.1

I also get this error in the last printf after the strcpy:

format ‘%s’ expects argument of type ‘char *’, but argument 2 has type ‘int’ error !**

Why is this happening, and how can I fix it?

Aucun commentaire:

Enregistrer un commentaire