免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 3149 | 回复: 1
打印 上一主题 下一主题

获取本地的IP地址 [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2011-07-21 13:33 |只看该作者 |倒序浏览
转:小楼

获取本地的IP地址
Windows下2种方法:
1.
使用拨号上网的话,一般都有一个本地ip和一个外网ip,使用python可以很容易的得到这两个ip
使用gethostbyname和gethostbyname_ex两个函数可以实现

  1. import socket
  2. localIP = socket.gethostbyname(socket.gethostname())#得到本地ip
  3. print "local ip:%s "%localIP

  4. ipList = socket.gethostbyname_ex(socket.gethostname())
  5. for i in ipList:
  6.     if i != localIP:
  7.        print "external IP:%s"%i
复制代码
2.

  1. import socket

  2. myname = socket.getfqdn(socket.gethostname())
  3. myaddr = socket.gethostbyname(myname)
复制代码
还有一种Linux下的方法可以用的是:

Uses the Linux SIOCGIFADDR ioctl to find the IP address associated with a network interface, given the name of that interface, e.g. "eth0". The address is returned as a string containing a dotted quad.

  1. import socket
  2. import fcntl
  3. import struct

  4. def get_ip_address(ifname):
  5.     s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
  6.     return socket.inet_ntoa(fcntl.ioctl(
  7.         s.fileno(),
  8.         0x8915,  # SIOCGIFADDR
  9.         struct.pack('256s', ifname[:15])
  10.     )[20:24])

复制代码
>>> get_ip_address('lo')
'127.0.0.1'

>>> get_ip_address('eth0')
'38.113.228.130'



Java版本:
  1. private Set getAllLocalHostIP() throws UnknownHostException{
  2.         Set result = new HashSet();
  3.         InetAddress addr = InetAddress.getLocalHost();
  4.         String hostName = addr.getHostName();
  5.         if(hostName.length() > 0){
  6.             InetAddress[] addrs = InetAddress.getAllByName(hostName);
  7.             if(addrs.length > 0){
  8.                 for(int i=0; i<addrs.length; i++){
  9.                     result.add(addrs[i].getHostAddress());
  10.                 }
  11.             }
  12.         }
  13.         
  14.         result.add("127.0.0.1");
  15.         return result;        
  16.     }
复制代码

论坛徽章:
0
2 [报告]
发表于 2011-07-21 17:01 |只看该作者
回复 1# 中关村村草


    怎么获得的都是127.0.0.1,不能直接得到局域网IP或者外网IP?
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP