输入在Char *中的“strtok”无法拆分IP地址和端口

时间:2014-11-13 14:12:06

标签: c strtok

我正在尝试将IP分成两部分,但它不起作用。 任何人都可以指出问题

    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");
        }
}

此处ipv4正在打印ipv4 : 100.100.100.100:65000 它应该打印100.100.100.100

2 个答案:

答案 0 :(得分:4)

strtok期望一个字符串作为输入。您需要更改以下内容:

添加:

#include <string.h>

变化:

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

工作示例:

#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);
}

输出:

  

Ipv4:100.100.20.1

     

端口:65000

答案 1 :(得分:0)

检查以下代码:

#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;
}