gpt4 book ai didi

c - 使用 getnameinfo() 解析以十六进制格式给出的 IP 地址

转载 作者:太空宇宙 更新时间:2023-11-04 02:49:30 25 4
gpt4 key购买 nike

我有一个用 C 编写的简单程序,它将 IP 地址解析为主机名。

#include <stdio.h>          /* stderr, stdout */
#include <netinet/in.h> /* in_addr structure */
#include <strings.h>
#include <arpa/inet.h>
#include <netdb.h>

int main(int argc, char **argv) {

if ( argc == 2) {

struct sockaddr_in sa;
sa.sin_family = AF_INET;
inet_pton(AF_INET, argv[1], &sa.sin_addr);

char node[NI_MAXHOST];
int res = getnameinfo((struct sockaddr*)&sa, sizeof(sa), node, sizeof(node), NULL, 0, 0);
if (res)
{
printf("&#37;s\n", gai_strerror(res));
return 1;
}
printf("%s\n", node);

return 0;
}
}

它工作正常(即 ./a.out 10.1.1.2)但我需要修改它以便它接受 HEX 格式的 IP 地址。

是否有将十六进制IP地址转换为十进制的函数?

最佳答案

我还没有测试过,但应该可以。

#include <stdio.h>          /* stderr, stdout */
#include <netinet/in.h> /* in_addr structure */
#include <strings.h>
#include <arpa/inet.h>
#include <netdb.h>

int main(int argc, char **argv) {

if ( argc == 2) {

struct sockaddr_in sa;
char a[2048] = {'\0'}; // placeholder not to overflow and initialised.
if( NULL == strchr(argv[1],'.') )
{
unsigned int unit0, uint1, uint2, uint3;
sscanf(argv[1], "%2x%2x%2x%2x", &uint0, &uint1, &uint2, &uint3);
sprintf(a,"%u.%u.%u.%u",uint0, uint1, uint2, uint3);
}
else
strcpy(a.argv[1]);
sa.sin_family = AF_INET;
inet_pton(AF_INET, a, &sa.sin_addr);

char node[NI_MAXHOST];
int res = getnameinfo((struct sockaddr*)&sa, sizeof(sa), node, sizeof(node), NULL, 0, 0);
if (res)
{
printf("&#37;s\n", gai_strerror(res));
return 1;
}
printf("%s\n", node);

return 0;
}
}

谢谢

关于c - 使用 getnameinfo() 解析以十六进制格式给出的 IP 地址,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23676965/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com