python, shell, golang获取本机IP地址

时间:2025-03-02 08:40:56
shell获取IP地址 /sbin/ifconfig -a|grep inet|grep -v 127.0.0.1|grep -v inet6|awk '{print $2}'|tr -d "addr:" /sbin/ifconfig|sed -n '/inet addr/s/^[^:]*:\([0-9.]\{7,15\}\) .*/\1/p' | grep -v 127.0.0.1 python获取IP地址 方法1: def get_local_ip(ifname): import socket, fcntl, struct s = (socket.AF_INET, socket.SOCK_DGRAM) inet = ((), 0x8915, ('256s', ifname[:15])) ret = socket.inet_ntoa(inet[20:24]) return ret print get_local_ip("eth0") 方法2: import os tmptxt=" /sbin/ifconfig eth0 |grep -w \"inet addr\" |cut -d: -f2 |cut -d\" \" -f1 " IPTMP=(tmptxt).read() IP=("\n","") print IP golang (转载) ======= package main import ( "net" "fmt" "strings" ) func main() { conn, err := ("udp", ":80") if err != nil { (()) return } defer () ((().String(), ":")[0]) }