gpt4 book ai didi

c - 尝试通过传递 ip (getnameinfo) 打印名称时出现段错误

转载 作者:行者123 更新时间:2023-11-30 18:41:19 31 4
gpt4 key购买 nike

我无法处理它,看不到我的代码有什么问题。

试图通过 IP 打印名称(我怀疑的网站),我三天都做不到,这让我很沮丧。

所以,我的代码:

/**
* task1.c -- getnameinfo() usage example
*
* Copyright (c) 2014 Ovchinnikov Alexzander
*
* This code is licensed under a MIT-style license.
*/

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>

#include <sys/types.h>
#include <sys/socket.h>
#include <netdb.h>

#include <arpa/inet.h>

#include <locale.h>

/**
* main
* @param argv количество параметров командной строки (учитая имя программы)
* @param argv массив строк-параметров командной строки
*/
int main(int argc, char *argv[])
{
int result;
struct sockaddr_in *sa; /* input */
char hbuf[NI_MAXHOST];

/*
* Инициализация подсистемы locale
*/
(void) setlocale(LC_ALL, "");

/*
* Должен быть один и только один аргумент командной строки
*/
if (2 != argc) {
fprintf(stderr, "usage: %s IPv4 address\n", argv[0]);
exit(EXIT_FAILURE);
}

/*
* Что-то делаем
*/
sa->sin_family = AF_INET;
sa->sin_port = htons(80);
result = inet_pton(AF_INET, argv[1], &(sa->sin_addr));
if (result <= 0){
if (result == 0){
fprintf(stderr, "Not in presentation format");
}else{
perror("inet_pton");
exit(EXIT_FAILURE);
}
}
memset(&sa->sin_zero, '\0', sizeof(sa->sin_zero));

/*
* Получить имя для адреса в argv[1]
*/
if (0 != (result = getnameinfo((struct sockaddr *)sa, sizeof(sa), hbuf, sizeof(hbuf), NULL, 0, NI_NAMEREQD))){
fprintf(stderr, "getnameinfo() error: %s\n", gai_strerror(result));
}else{
fprintf(stdout, "host:%s\n", hbuf);
}

return 0;
}

编译时:

gcc -Wall -o task1_2 task1_2.c

,我明白了:

task1_2.c:49:20: warning: ‘sa’ may be used uninitialized in this function
[-Wmaybe-uninitialized]

sa->sin_family = AF_INET;

当像这样运行时:

./task1_2 87.240.131.120

,我遇到段错误。

最佳答案

您尚未为sa分配内存

sa = (struct sockaddr_in*) malloc(sizeof(struct sockaddr_in)); 

关于c - 尝试通过传递 ip (getnameinfo) 打印名称时出现段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22310469/

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