How to obtain an IP address

Source: Internet
Author: User

Python can be used to obtain the IP address of the local machine in a simple way. However, the methods in Windows and Linux are slightly different,

Method 1 for obtaining an IP address in Windows

When using dial-up Internet access, there is usually a local IP address and an Internet IP address. Using python, you can easily get the two IP addresses and use the gethostbyname and gethostbyname_ex functions to implement them.

  Import   socket  localip =  socket .  gethostbyname   (  socket .  gethostname   ( )  )   # obtain the local IP address   Print   "local IP: % s " % localip iplist =  socket .  gethostbyname_ex   (  socket .  gethostname   ( )  )   for  I  in  iplist: 
  
    If  I 
   !  = localip: 
    Print  
    "external IP: % s " 
   % I 
  
Method 2
 
Import SocketMyname =Socket.Getfqdn(Socket.Gethostname())Myaddr =Socket.Gethostbyname(Myname)
How to obtain IP addresses in Linux

The above method can also be used in Linux. In addition, you can use the following method to obtain the local IP address in 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.

 Import   Socket  Import  Fcntl  Import   Struct  Def Get_ip_address ( Ifname ) : S = Socket . Socket  (  Socket . Af_inet , Socket . Sock_dgram  )      Return   Socket . Inet_ntoa  ( Fcntl . IOCTL  ( S. Fileno  (  ) , 0x8915, # Siocgifaddr          Struct . Pack  (  '256s' , Ifname [ : 15  ]  )      )  [  20 : 24  ] ) 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.