获取127.0.1.1而不是192.168.1。* ip ubuntu python

时间:2019-03-22 09:31:35

标签: python python-3.x sockets python-sockets

我是python的新手。我想获取系统的ipaddress。我在局域网中连接。当我使用以下代码获取ip时,它显示的是127.0.1.1,而不是192.168.1.32。为什么不显示局域网IP。那我怎样才能得到我的局域网IP。每个教程仅以这种方式显示。我还通过连接移动热点进行了检查。尽管如此,它仍然显示相同的内容。

import socket    
hostname = socket.gethostname()    
IPAddr = socket.gethostbyname(hostname)    
print("Your Computer Name is:" + hostname)    
print("Your Computer IP Address is:" + IPAddr)    

输出:

Your Computer Name is:smackcoders
Your Computer IP Address is:127.0.1.1

必需的输出:

Your Computer Name is:smackcoders
Your Computer IP Address is:192.168.1.32

5 个答案:

答案 0 :(得分:1)

How can I get the IP address of eth0 in Python?

s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.connect(("8.8.8.8", 80))
print s.getsockname()[0]

答案 1 :(得分:1)

根据上述“ / etc / hosts”文件的内容,您具有一个IP地址,其主机名映射为“ 127.0.1.1”。这导致名称解析得到127.0.1.1。您可以尝试删除/注释此行并重新运行。

答案 2 :(得分:1)

我的raspi遇到了同样的问题。

public ActionResult GetProductInReceipt(int id, int **SaleQuantity**)
{

    ProductSale productSale = db.ProductSales.FirstOrDefault(a => a.ProductId == id);
    Product product = db.Products.FirstOrDefault(a => a.ProductId == id);

    List<ProductSale> ProductSales = (List<ProductSale>)Session["ProductSale"];
    if (ProductSales == null)
    {
        ProductSales = new List<ProductSale>();
    }

    ProductSales.Add
    (
        new ProductSale()
        {
            ProductId = product.ProductId,
            SaleId = (db.Sales.Max(a => a.SaleId))+1,
            SalePrice = product.SellingPrice,
            SaleQuantity = **SaleQuantity**,
            TotalPrice = SaleQuantity * product.SellingPrice,
            Product = db.Products.FirstOrDefault(a => a.ProductId == product.ProductId)
        }
    );
    Session["ProductSale"] = ProductSales;}

现在,如果我打印host_addr,它将打印127.0.1.1。 所以我发现了这个:https://www.raspberrypi.org/forums/viewtopic.php?t=188615#p1187999

host_name = socket.gethostname()`
host_addr = socket.gethostbyname(host_name)

它奏效了。

答案 3 :(得分:0)

此解决方案在Windows上对我有效。如果您使用的是Linux,则可以尝试以下代码行:

IPAddr = socket.gethostbyname(socket.getfqdn())

答案 4 :(得分:0)

我遇到您面临的同样问题。但是我借助自己的想法获得了解决方案,而且不用担心它使用起来很简单。 如果您熟悉linux,则应该听到ifconfig命令,该命令返回有关网络接口的信息,并且您还应该了解grep命令,该命令可以过滤包含指定单词的行 现在只需打开终端并输入

ifconfig | grep 255.255.255.0

然后点击enter,您将像下面这样单独获得wlan inet地址行

inet 192.168.43.248  netmask 255.255.255.0  broadcast 192.168.43.255
在您的终端机中

在您的python脚本中只需插入

#!/usr/bin/env python
import subprocess
cmd = "ifconfig | grep 255.255.255.0"
inet = subprocess.check_output(cmd, shell = True)
inet = wlan.decode("utf-8")
inet = wlan.split(" ")
inet_addr = inet[inet.index("inet")+1]
print(inet_addr)

此脚本返回您的本地IP地址,该脚本对我有用,我希望这对您的linux计算机也适用 一切顺利