【发布时间】:2016-10-28 22:05:17
【问题描述】:
我正在尝试将 IP 地址(当前为 IPv4,但可识别 IPv6)从 int 数组格式转换为格式化字符串。我正在开发 Ubuntu Linux。
我区分了 IPv4 和 IPv6 地址,然后尝试将 int 数组转换为字符串。
这是我正在使用的代码:
#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 ipv6\n");
else
printf("\nwrong ipv6\n");
}
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 = %s\n", ipaddr);
strcpy(&m_ip[0], ipaddr);
printf("\nafter strcpy = %s\n", m_ip[0]);
}
}
这个输出是错误的:
ipaddr = 0.0.0.10
实际上应该是:
ipaddr = 10.1.35.1
我在strcpy 之后的最后一个printf 中也收到此错误:
格式“%s”需要“char *”类型的参数,但参数 2 有“int”类型错误!**
为什么会发生这种情况,我该如何解决?
【问题讨论】:
标签: c string network-programming ipv6 ipv4