Various perl methods for obtaining local ip addresses on Linux

Source: Internet
Author: User
Tags call shell

When we discuss how to use Gearman for distributed processing, each machine needs to register an independent job for information feedback. However, for convenience, the Gearman: Worker script register_function code must be universal, so I thought of using their respective IP addresses as job names ~

So how can I get the local ip address as func in the worker script?

The first method is to call shell:

$ip = `ifconfig eth0|grep -oE '([0-9]{1,3}\.?){4}'|head -n 1`;

Note: The input here is fixed, so the simple [0-9] {1, 3} is. If the ip address is verified in a web program or another place, you need to be more rigorous!

Or

$ip = `ifconfig eth0|awk -F: '/inet addr/{split($2,a," ");print a[1];exit}'`;

Well, it seems too much perl, and it is not good to call external shells frequently. The second is:

open FH,"ifconfig eth0|";while(<FH>){last unless /inet addr:((\d{1,3}\.?){4})/;print $1;}

It looks a little more perl, although it is essentially the same as calling the shell and grep methods above.

Third, a little more perl, purely reading files:

open FH,'<','/etc/sysconfig/network-scripts/ifcfg-eth0';while(<FH>){next unless /IPADDR\s*=\s*(\S+)/;print $1;}

Further, if the rh system is not necessarily required, read/etc/issue, determine whether the network configuration file is/etc/sysconfig/network-script/ifcfg-eth0 or/etc/network/interfaces or others, and then write different processing methods according to different releases ...... Are you planning to write the module yourself?

Well, let's fully appreciate the charm of CPAN. Go to search and find a number of modules, such as Sys: HostIP, Sys: HostAddr, and Net: Inetface. Fourth:

use Sys::HostAddr;my $interface = Sys::HostAddr->new(ipv => '4', interface => 'eth0');print $interface->main_ip;

But let's look at the pm file and sweat. These modules call the ifconfig command, but they are encapsulated according to the different versions of the release.

Is there a solution? Also, let's look at the fifth type:

perl -MPOSIX -MSocket -e 'my $host = (uname)[1];print inet_ntoa(scalar gethostbyname($host))';

However, some children's shoes have said that this may be caused by the hostname, which leads to 127.0.0.1 ......

Then there is another trick. The strace ifconfig command shows that linux uses the ioctl command to obtain the ip address of the network interface. So we can also use ioctl!

As follows:

#!/usr/bin/perluse strict;use warnings;use Socket;require 'sys/ioctl.ph';sub get_ip_address($) {    my $pack = pack("a*", shift);    my $socket;    socket($socket, AF_INET, SOCK_DGRAM, 0);    ioctl($socket, SIOCGIFADDR(), $pack);    return inet_ntoa(substr($pack,20,4));};print get_ip_address("eth0");

The advantage is that only the core module is called, and other modules are not required when distributing scripts.

Note: This is actually modified according to a py script on the Internet. The py version is as follows:

#!/usr/bin/pythonimport socketimport fcntlimport structdef 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])print get_ip_address('eth0')

Original article: http://chenlinux.com/2011/09/20/get-ip-address-by-perl-on-linux/

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.