Can not split the IP address and port using "strtok" where input is in Char *

1.8k Views Asked by At

I am trying so break IP into two parts but it's not working. can anyone point out the Problem

    void encode_ip_with_port(unsigned char *tlvbuf) {
    // 100.100.100.100:65000
    // abcd:abcd:abcd:abcd:abcd:abcd:abcd:abcd:12344
        // Ipv4
        struct in_addr addr;
        // Remove Port
        char *ipv4 = NULL ;
        char *port = NULL;
        printf("Input : %s\n ",tlvbuf);
        char input = ":";
        //char str[]="this, by the way, is a 'sample'";
        ipv4 = strtok(tlvbuf, &input);
        port = strtok(NULL, ":");
        printf("Ipv4 : %s\n",ipv4);
                printf("port : %s\n",port);
        if (!inet_pton(AF_INET,ipv4 , &addr)) {
            fprintf(stderr, "Could not convert address\n");
        }
}

Here ipv4 is printing ipv4 : 100.100.100.100:65000 it should print 100.100.100.100

2

There are 2 best solutions below

3
On BEST ANSWER

strtok expects a string as input. You need to change the following:

Add:

#include <string.h>

Change:

    char *input = ":";  // char --> char*
    ipv4 = strtok(tlvbuf, input);  // removed &

Working example:

#include<stdio.h>
#include<string.h>
main()
{
    char *ipv4, *port;
    char tlvbuf[80] = "100.100.20.1:65000";
    char* input = ":";
    ipv4 = strtok(tlvbuf, input);
    port = strtok(NULL, ":");
    printf("Ipv4 : %s\n",ipv4);
    printf("port : %s\n",port);
}

Output:

Ipv4 : 100.100.20.1

port : 65000

6
On

Check the below code:

#include <stdio.h>
#include<stdlib.h>
#include <string.h>

int main()
{
char a[30] = "100.100.100.100:2500";
char *p = NULL;
p = strtok(a,":");

printf("%s\n",p);

p = strtok(NULL,":");
printf("%s\n",p);
return 0;
}