转自:http://www.oschina.net/code/snippet_157439_18019
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.socket(socket.AF_INET, socket.SOCK_DGRAM) inet = fcntl.ioctl(s.fileno(), 0x8915, struct.pack('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=os.popen(tmptxt).read() IP=IPTMP.replace("\n","") print IP golang (转载) ======= package main import ( "net" "fmt" "strings" ) func main() { conn, err := net.Dial("udp", "google.com:80") if err != nil { fmt.Println(err.Error()) return } defer conn.Close() fmt.Println(strings.Split(conn.LocalAddr().String(), ":")[0]) }
有疑问加站长微信联系(非本文作者)