需要帮助理解 C 程序来查找机器的 IP 地址
我没有收到有关查找机器 IP 地址的作业。我需要帮助理解这段代码的逻辑。我们大学实验室使用代理服务器;这段代码可以在没有代理的计算机上运行吗?
#include <stdio.h> /* stderr, stdout */
#include <netdb.h> /* hostent struct, gethostbyname() */
#include <arpa/inet.h> /* inet_ntoa() to format IP address */
#include <netinet/in.h> /* in_addr structure */
int main(int argc, char **argv) {
struct hostent *host; /* host information */
struct in_addr h_addr; /* internet address */
if (argc != 2) {
fprintf(stderr, "USAGE: nslookup <inet_address>\n");
exit(1);
}
if ((host = gethostbyname(argv[1])) == NULL) {
fprintf(stderr, "(mini) nslookup failed on '%s'\n", argv[1]);
exit(1);
}
h_addr.s_addr = *((unsigned long *) host->h_addr_list[0]);
fprintf(stdout, "%s\n", inet_ntoa(h_addr));
exit(0);
}
I am not getting this assignment about finding the IP address of the machine. I need help understanding the logic of this code. Our college lab uses proxy server; will this code work on a computer without proxy?
#include <stdio.h> /* stderr, stdout */
#include <netdb.h> /* hostent struct, gethostbyname() */
#include <arpa/inet.h> /* inet_ntoa() to format IP address */
#include <netinet/in.h> /* in_addr structure */
int main(int argc, char **argv) {
struct hostent *host; /* host information */
struct in_addr h_addr; /* internet address */
if (argc != 2) {
fprintf(stderr, "USAGE: nslookup <inet_address>\n");
exit(1);
}
if ((host = gethostbyname(argv[1])) == NULL) {
fprintf(stderr, "(mini) nslookup failed on '%s'\n", argv[1]);
exit(1);
}
h_addr.s_addr = *((unsigned long *) host->h_addr_list[0]);
fprintf(stdout, "%s\n", inet_ntoa(h_addr));
exit(0);
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这里感兴趣的 2 个关键方法是:
尝试具体一点,您在理解代码时遇到问题的地方。
该代码适用于我。
返回主机 IP。
The 2 key methods of interest here are:
Try to be specific, where are you having problem understanding the code.
The code works with me.
returns host ip.
netdb.h
- 网络数据库操作的定义arpa/inet.h
- 互联网操作的定义netinet/in.h
- 互联网地址系列gethostname()
函数返回当前计算机的标准主机名。inet_ntoa(h_addr)
将 IP 地址从 32 位网络格式转换回点分十进制。这些是基本的理解术语。最重要的是使用
google
了解详细信息。netdb.h
- definitions for network database operationsarpa/inet.h
- definitions for internet operationsnetinet/in.h
- Internet address familyThe
gethostname()
function returns the standard host name for the current machine.inet_ntoa(h_addr)
To convert an IP address from 32-bit network format back to dotted decimal.These are the basic understanding terms. Most importantly use
google
for detail.实际上,gethostbyname 函数执行一个 DNS 请求,该请求返回 hostent 结构字段。
使用wireshark 嗅探网络来查看流量可能会很有趣。
Actually, the gethostbyname function performs a DNS request which returns the hostent structure filed.
It could be interesting for you to snif the network with wireshark for instance to look what the traffic looks like.