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  ] )