警告:从不兼容的指针类型传递“ inet_aton”的参数2。

时间:2019-05-29 10:46:33

标签: c pointers error-handling compiler-errors inet-aton

我不知道此错误的含义以及解决方法。

我一直在YouTube上关注Sock)et Programming Tutorials In C For Beginners | Part 2 by Eduonix,但是我无法从这个人那里运行任何东西,代码来自他的教程。

如果有人可以帮助我了解此错误的含义以及解决方法?

这是错误:

inet_aton(address, &remote_address.sin_addr.s_addr);
                   ^

[1007:1003 0:6758] 09:30:39 Wed May 29 [kristjan@Kundrum:pts/5 +1] ~/C_Programming
$ gcc http_client_tcp.c -o http_client_tcp
http_client_tcp.c: In function ‘main’:
http_client_tcp.c:24:24: warning: passing argument 2 of ‘inet_aton’ from incompatible pointer type [-Wincompatible-pointer-types]
     inet_aton(address, &remote_address.sin_addr.s_addr);
                        ^
In file included from http_client_tcp.c:8:0:
/usr/include/arpa/inet.h:73:12: note: expected ‘struct in_addr *’ but argument is of type ‘in_addr_t * {aka unsigned int *}’
 extern int inet_aton (const char *__cp, struct in_addr *__inp) __THROW;
            ^~~~~~~~~

我在Visual Studio Code中使用Debian Linux 9.9拉伸和编码,但是只有在shell中编译时,该错误才不会在Visual Code编辑器/调试器中出现。

代码如下:

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

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

#include <netinet/in.h>
#include <arpa/inet.h>

#include <unistd.h> // for close

int main(int argc, char *argv[])
{
    char *address;
    address = argv[1];

    int client_socket;
    client_socket = socket(AF_INET, SOCK_STREAM, 0);

    // connect to an address
    struct sockaddr_in remote_address;
    remote_address.sin_family = AF_INET;
    remote_address.sin_port = htons(80);
    inet_aton(address, &remote_address.sin_addr.s_addr);

    connect(client_socket, (struct sockaddr *) &remote_address, sizeof(remote_address));

    char request[] = "GET / HTTP/1.1\r\n\r\n";
    char response[4096];

    send(client_socket, request, sizeof(request), 0);
    recv(client_socket, &response, sizeof(response), 0);

    printf("response from server: %s\n", response);
    close(client_socket);

    return 0;
}

2 个答案:

答案 0 :(得分:5)

该教程不好,正确的代码是

inet_aton(address, &remote_address.sin_addr);

remote_address.sin_addrin_addr类型,其定义是

struct in_addr {
    unsigned long s_addr;
};

&remote_address.sin_addr.s_addr&remote_address.sin_addr的值将为相同的地址,但前者的类型错误。原始文件将使用默认设置在GCC中使用警告进行编译,但这是约束违反

对于Visual Studio代码,您应该看起来更难一点,或者也许用-Werror进行编译!


该寻找更好的教程了。

答案 1 :(得分:3)

检查类型。从man page

  

int inet_aton(const char *cp, struct in_addr *inp);

第二个参数是指向struct in_addr类型变量的指针。

在您的代码中,您将remote_address定义为

 struct sockaddr_in remote_address;

其中struct sockaddr_in被定义为

struct sockaddr_in {
    short            sin_family;   // e.g. AF_INET
    unsigned short   sin_port;     // e.g. htons(3490)
    struct in_addr   sin_addr;     // ***** this is the target
    char             sin_zero[8];  // zero this if you want to
};

所以,您的用法

 inet_aton(address, &remote_address.sin_addr.s_addr);

应该是

inet_aton(address, &(remote_address.sin_addr)); // explicit parenthesis to clarify type