Portál AbcLinuxu, 3. prosince 2025 13:25
#include < sys/socket.h >
#include < netinet/in.h >
#include < arpa/inet.h >
#include < stdio.h >
#include < stdlib.h >
int main(int argc, char *argv[])
{
struct in_addr addr;
unsigned char buf[sizeof(struct in6_addr)];
char str[INET6_ADDRSTRLEN];
if (argc<2)
{
fprintf(stderr, "IPv4 address required as an argument.\n");
exit(EXIT_FAILURE);
}
if (inet_aton(argv[1], &addr) == 0)
{
perror("inet_aton");
exit(EXIT_FAILURE);
}
if (inet_pton(AF_INET, argv[1], buf) != 1)
{
perror("inet_pton");
exit(EXIT_FAILURE);
}
if (inet_ntop(AF_INET6, buf, str, INET6_ADDRSTRLEN)==NULL)
{
perror("inet_ntop");
exit(EXIT_FAILURE);
}
printf("%s\n", str);
exit(EXIT_SUCCESS);
}
Řešení dotazu:
#define _GNU_SOURCE
#include < string.h>
#include < sys/socket.h>
#include < netinet/in.h>
#include < arpa/inet.h>
#include < stdio.h>
#include < stdlib.h>
#define IPV6_ADDRESS_SIZE sizeof(struct in6_addr)
int main(int argc, char *argv[])
{
struct in_addr addr;
unsigned char buf_v4[sizeof(struct in_addr)];
unsigned char buf_v6[IPV6_ADDRESS_SIZE] = {0};
unsigned char str[INET6_ADDRSTRLEN];
if (argc<2)
{
fprintf(stderr, "IPv4 address required as an argument.\n");
exit(EXIT_FAILURE);
}
if (inet_aton(argv[1], &addr) == 0)
{
perror("inet_aton");
exit(EXIT_FAILURE);
}
if (inet_pton(AF_INET, argv[1], buf_v4) != 1)
{
perror("inet_pton");
exit(EXIT_FAILURE);
}
*(buf_v6 + IPV6_ADDRESS_SIZE - 5) = 255;
*(buf_v6 + IPV6_ADDRESS_SIZE - 6) = 255;
mempcpy(buf_v6 + IPV6_ADDRESS_SIZE - 4, buf_v4, 4);
if (inet_ntop(AF_INET6, buf_v6, str, INET6_ADDRSTRLEN)==NULL)
{
perror("inet_ntop");
exit(EXIT_FAILURE);
}
printf("%s\n", str);
exit(EXIT_SUCCESS);
}
Tiskni
Sdílej:
ISSN 1214-1267, (c) 1999-2007 Stickfish s.r.o.