与inet_ntoa()函数混淆。 [英] Troubles with the inet_ntoa() function.

查看:160
本文介绍了与inet_ntoa()函数混淆。的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

你好!我正在尝试编写一个使用原始套接字的程序,但是当我尝试编译这一行时:

 printf(   Indirizzo origine:%s \ n,inet_ntoa(ip-> saddr)); 



我收到此错误:

警告:格式'%s'需要类型'char *'的参数,但参数2的类型为'int'[ -Wformat =] 
printf(Indirizzo origine:%s \ n,inet_ntoa(ip-> saddr));



ip声明如下:

  struct  iphdr * ip; 



是不是inet_ntoa()函数返回一个字符串?我做错了什么?

解决方案

我通过使用inet_ntop()函数而不是我正在使用的第一个函数来解决它。


< blockquote>是的,通过文档它应该返回 char * 。检查是什么。也许你包含了错误的标题和一个不同的函数,但是更有可能的是,由于一些奇怪的原因,你在声明函数的点之前使用了这个函数调用。这种耻辱只会因为你使用C而不是C ++而发生。



Stackoverflow expert 表明



inet_ntoa的错误返回类型是旧C规则的结果,它指出如果你尝试使用没有事先声明的函数,那么编译器必须假定该函数返回一个int并获取一个未知(但固定)的参数。假定的返回类型与函数的实际返回类型之间的不匹配会导致未定义的行为,这表现为您的案例中的崩溃。



解决方案是包括inet_ntoa的正确标题。

我建​​议更多:使用C ++代替它,它至少可以防止一些完全不必要的麻烦。



< DD> -SA

Hi guys! I'm trying to write a program that uses raw sockets, but when I try to compile this line:

printf("Indirizzo origine: %s\n", inet_ntoa(ip->saddr));


I get this error:

warning: format ‘%s’ expects argument of type ‘char *’, but argument 2 has type ‘int’ [-Wformat=]
        printf("Indirizzo origine: %s\n", inet_ntoa(ip->saddr));


"ip" is declared as follows:

struct iphdr *ip;


Isn't inet_ntoa() function returning a string? What am I doing wrong?

解决方案

I solved it by using the inet_ntop() function instead of the first I was using.


Yes, by documentation it's supposed to return char*. Check up what is that. Maybe you included wrong header, and a different function, but it's more likely that, by some weird reason, you use this function call before the point where the function is declared. This shame could take place only because you use C, not C++.

Stackoverflow expert suggests:


The incorrect return-type for inet_ntoa is the result of an old C rule that states that if you try to use a function without a prior declaration, then the compiler must assume the function returns an int and takes an unknown (but fixed) number of arguments. The mismatch between the assumed return type and the actual return type of the function results in undefined behaviour, which manifests itself as a crash in your case.

The solution is to include the correct header for inet_ntoa.

I would suggest more: use C++ instead, it would guard you at least from some of totally unnecessary troubles.

—SA


这篇关于与inet_ntoa()函数混淆。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆