如何使用 gethostbyname() 检测您的 IP/名称
有没有办法从gethostname()
获取IP号码?
我们为实验室中的计算机随机生成 IP 地址。我们使用 gethostbyname(
来获取计算机的 IP。
我们本质上要做的就是比较从 gethostbyname() 获得的 ip 与从 gethostname() 获得的 IP。
我们尝试过:
struct hostent* host;
char temp[MAX_LEN];
gethostname(temp, MAX_LEN);
host = gethostbyname(<random ip address>)
if(host->h_name == temp) printf("They are the same\n");
问题是,host->h_name 是 '172.125.45.1' (我这样做了 向上),温度为'u-my_comp'
所以我们无法比较字符串,因为一个给出了计算机的名称 (u-my_comp),另一个给出了 ip...
无论如何使这些函数返回相同类型的值?
我们尝试过做类似的事情,
gethostname(temp, 24)
temp_host = gethostbyname(temp)
希望现在我们可以将 temp_host->h_name 与 host->h_name 进行比较......但是,是的,这也不起作用。
有什么想法吗?
谢谢!
is there a way to get the IP number from gethostname()
?
We are randomly generating IP addresses for the computers in the lab we are in. We use gethostbyname(<random ip>)
to get the IP of a computer.
What we want to do essentially is compare the ip that we get from gethostbyname() with what we get from gethostname().
We tried:
struct hostent* host;
char temp[MAX_LEN];
gethostname(temp, MAX_LEN);
host = gethostbyname(<random ip address>)
if(host->h_name == temp) printf("They are the same\n");
The problem is, is that host->h_name is '172.125.45.1' (i made that
up) and temp is 'u-my_comp'
so we cant compare the strings cause one gives us the name of the computer (u-my_comp), and the other gives the ip...
Is there anyway to make these functions return the same type of value?
we have tried doing something like
gethostname(temp, 24)
temp_host = gethostbyname(temp)
in hopes that now we could compare temp_host->h_name with host->h_name...but yeah, that didnt work either.
Any ideas?
thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
gethostbyname()
用于将主机名转换为套接字地址。如果您提供的“主机名”是一个点分四组 IPv4 地址,那么这将是您在结果的h_name
参数中获得的全部内容。要将套接字地址转换回名称,您需要使用配套函数
gethostbyaddr()
- 但您不需要,因为gethostbyname()
和gethostbyaddr() 已弃用。相反,您应该使用
getaddrinfo()
和getnameinfo()
。例如:
gethostbyname()
is for converting a hostname into a socket address. If the "hostname" you supply is a dotted-quad IPv4 address, that will be all you get in theh_name
parameter of the result.To convert a socket address back into a name what you want is the companion function
gethostbyaddr()
- except that you don't, because bothgethostbyname()
andgethostbyaddr()
are deprecated. Instead, you should be usinggetaddrinfo()
andgetnameinfo()
.For example:
如果您调用:(
已分配 myhost),那么您将有两个要比较的 hostent 结构 - 您将获得目标查询主机和当前主机的 IP 地址列表(而不仅仅是当前主机的主机名)。
If you call:
(having allocated myhost) then you will have two hostent structures you will compare - you will have the IP address lists for both the target query host and the current host (not just the hostname for the current host).