Linux——获取IP及其中发现的问题

文章讲述了在学习网络编程过程中遇到的获取本机IP地址的不同方法,包括通过http://test-ipv6.com/测试、百度查询公网IP、Python的socket模块以及bash命令ifconfig,每种方法得到的IP地址不同,反映出网络连接的复杂性,如公网IP、私网IP、IPv4、IPv6等概念。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

由于最近在学习网络编程,喜欢玩IP地址。

首先,我需要搞清楚如何获得本机IP。

===========================================11.04=================================================
我去,更奇怪的事情出现了。
1、
我用http://test-ipv6.com/做IPv6测试,测试结果为0/10.
但这不重要,重要的是今天(11.04)它告诉我本机IP是:111.17.191.79
2、
当我百度关键字“公网IP”时,百度告诉为我的IP地址为:219.146.245.35
3、
当我使用python获取IP地址时:
Python 3.3.3 (default, Sep  6 2014, 10:53:40) 
[GCC 4.4.6 20120305 (Red Hat 4.4.6-4)] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import socket
>>> print(socket.gethostbyname(socket.gethostname()))
219.146.13.36
IP地址:219.146.13.36
4、当我调用bash命令:ifconfig时:
ppp0      Link encap:Point-to-Point Protocol
          inet addr:180.201.198.204  P-t-P:192.168.100.1  Mask:255.255.255.255
          UP POINTOPOINT RUNNING NOARP MULTICAST  MTU:  Metric:
          RX packets: errors: dropped: overruns: frame:
          TX packets: errors: dropped: overruns: carrier:
          collisions: txqueuelen:
          RX bytes: (9.8 MiB)  TX bytes: (1.4 MiB)

IP地址:180.120.198.204

四种方法得到四个IP地址。很有意思啊。
=================================================尝试分析==========================================================
1、第一种方法和第二种方法得到的IP地址来源原理未知,暂不做讨论。
2、利用python获得IP地址,用到了两个函数socket.gethostname()、socket.gethostbyname()
python文档的解释:
socket.gethostname()
Return a string containing the hostname of the machine where the Python interpreter is currently executing.
If you want to know the current machine’s IP address, you may want to use gethostbyname(gethostname()). 
This operation assumes that there is a valid address-to-host mapping for the host, and the assumption does not always hold.
 
Note: gethostname() doesn’t always return the fully qualified domain name; use getfqdn() (see above).
socket.gethostbyname()
Translate a host name to IPv4 address format. The IPv4 address is returned as a string, such as '100.50.200.5'. If the host name is 
an IPv4 address itself it is returned unchanged. See gethostbyname_ex() for a more complete interface. gethostbyname() does not 
support IPv6 name resolution, and getaddrinfo() should be used instead for IPv4/v6 dual stack support.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

lmr廖

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值