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


    由于最近在学习网络编程,喜欢玩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:1492  Metric:1
              RX packets:11163 errors:0 dropped:0 overruns:0 frame:0
              TX packets:11531 errors:0 dropped:0 overruns:0 carrier:0
              collisions:0 txqueuelen:3 
              RX bytes:10325636 (9.8 MiB)  TX bytes:1527057 (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.






  • 相关阅读:
    python流程控制
    数据类型
    python之初接触
    使用 HttpWebRequest 向网站提交数据
    在 ASP.NET MVC4 中使用 NInject
    第一篇 微信商城 开发前的准备工作
    (一)模块基础
    函数之递归、匿名函数及内置方法
    装饰器的使用原理
    mybatis返回list
  • 原文地址:https://www.cnblogs.com/Simon-xm/p/4070037.html
Copyright © 2020-2023  润新知