【问题标题】:Inspecting C Header Files Further进一步检查 C 头文件
【发布时间】:2016-07-19 12:19:17
【问题描述】:

我正在通过查看 Microsoft Visual Basic 2013 中工作包嗅探器的代码来学习 c 中的网络。

下面的代码创建了一个指向hostent结构的指针,获取localhost主机名,并将其加载到名为hostent结构hostent结构中 em>本地。

struct hostent *local;
gethostname(hostname, sizeof(hostname))
local = gethostbyname(hostname);

下一部分使地址以点分十进制形式打印。

for (i = 0; local->h_addr_list[i] != 0; ++i)
{
    memcpy(&addr, local->h_addr_list[i], sizeof(struct in_addr));
    printf("  Interface Number : %d Address : %s\n",i,inet_ntoa(addr));
}

现在,我想了解这一切是如何运作的以及更多。 . .

假设我想了解 inet_ntoa(),我右键单击并选择 Go To DefinitionGo To Declaration,它会将我发送到 WinSock2.h 表明:

inet_ntoa(
    __in struct in_addr in
);

这似乎是向我显示参数,而不是函数的工作原理或返回值。这意味着我必须参考 MSDN 以了解每次发生的情况。

我的问题是:读取正在发生的事情的代码在哪里,所以我不必使用文档?

例如inet_ntoa函数内容在哪里?

【问题讨论】:

  • inet_ntoa 在系统 DLL 中实现,特别是 Ws2_32.dll。没有可用的 Microsoft 源。您将能够找到可用于其他平台的开源实现。 Linux 文档在这里linux.die.net/man/3/inet_ntoa
  • 这在很多c库中都有实现,例如glibc实现了它,你可以阅读它的代码,因为你可以下载整个glibc .它肯定没有在头文件中实现。
  • 这是来自 WinSock2.h 的 full 引用吗?因为函数声明似乎缺少返回类型,这根本不应该工作。

标签: c++ c visual-studio-2013 header-files msdn


【解决方案1】:

你在这里:

#include <stdio.h>
#include <stdlib.h>
#include <arpa/inet.h>

/* The interface of this function is completely stupid, it requires a
   static buffer.  We relax this a bit in that we allow one buffer for
   each thread.  */

static __thread char buffer[18];

char *inet_ntoa (struct in_addr in)
{
   unsigned char *bytes = (unsigned char *) &in;
   __snprintf (buffer, sizeof (buffer), "%d.%d.%d.%d",
               bytes[0], bytes[1], bytes[2], bytes[3]);

  return buffer;
}

取自 inet_ntoa.cglibc 2.23

请记住,glibc 是开源的,所以如果您想稍微探索一下并了解其中的原理,请不要犹豫并下载它!

问候

【讨论】:

  • @Phoenix 您可以下载 glibc 代码,然后从代码的根目录执行find . -type f -name '*.c' -exec grep -nH --color "inet_ntoa" {} \; 之类的操作。然后就可以找到实现的地方了。
  • 最好提供一个指向源的实时链接:sourceware.org/git/?p=glibc.git;a=blob;f=inet/…(并不是说我期望这个会改变很多:P ...另外,还有有趣的评论)
  • 切题:这里有一个线程讨论这个函数的可疑接口和inet_ntop() 的可用性,它使用了我们许多人一直期望的那种接口:stackoverflow.com/questions/1705885/…跨度>
  • 我想已经足够好了,但 OP 要求提供 Microsoft 代码,这是另一回事。
  • @SvenNilsson 好点。我想这取决于 OP 是否只想知道函数 must 做什么,而不是具体如何做。但是,撇开 API 文档不谈,函数签名通常会使前者相当清楚。我很困惑为什么它在 OP 的引用中似乎缺少返回类型。
猜你喜欢
  • 1970-01-01
  • 2018-09-26
  • 1970-01-01
  • 2022-01-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多