我正在尝试将IP地址(当前为IPv4,但可识别IPv6)从整数数组格式转换为格式化字符串。我正在使用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
我也在:printf
之后的最后一次收到此错误strcpy
:
格式'%s'期望的参数类型为'char *',但是参数2的类型为'int'错误!**
为什么会发生这种情况,我该如何解决?
这是一个可行的版本。您的代码的问题是,strtok()正在修剪字符串's3'。到n == 4时,字符串只剩下“ 10”。
#include <stdio.h>
#include <string.h>
#include <arpa/inet.h>
#include <malloc.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";
char *s4 = malloc(strlen(s3)+1);
strcpy(s4, s3); //You can save the original string.
/* 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(s4); //use the intact string s4, instead of 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);
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句