Michael C. Toren on Tue, 24 Dec 2002 14:14:22 -0500


[Date Prev] [Date Next] [Thread Prev] [Thread Next] [Date Index] [Thread Index]

Re: [PLUG] proc filesystem


> How can I obtain my ipaddress from the proc filesystem.

Unfortunately, this is very hard to do in a portable way from the shell.
If you only intend to run the script on one or two systems, parsing the
output of ifconfig is probably your best shot, however keep in mind that
it's output can be wildly different on various flavors of unix-like
operating systems.

> I was thinking of doing it like that:
> cat /proc/net/arp | awk '{print $1}'
> which works on my computer, but not on most.

I wouldn't expect that to work on any Linux system, as only remote entries
are added to the arp table, not local entries.

Also, keep in mind that your system probably already has more than one IP
address -- for instance, your source address will be different if you're
connecting to localhost than if you're connecting to a random host on the
internet at large.  If you're interested in knowing what your source
address will be when sending packets to a particular destination, and if
it's acceptable in this case use a small perl script from your shell, the
following may be of use to you and should be very portable[1].  It takes
as an argument on the command line the destination you'd like to reach,
defaulting to 207.106.1.2 (ns1.netaxs.com) if none is specified.

	# mct, Tue Dec 24 13:06:10 EST 2002
	use Socket;
	my $host = shift || "207.106.1.2";
	my $udp = getprotobyname("udp") or die "getprotobyname: $!\n";
	socket(S, PF_INET, SOCK_DGRAM, $udp) or die "socket: $!\n";
	my $sin = sockaddr_in 42, inet_aton $host;
	connect S, $sin or die "connect: $!\n";
	print inet_ntoa((sockaddr_in getsockname S)[1]), "\n";

-mct

[1] Successfully tested on:
	- Linux quint 2.4.19 #1 Sun Aug 4 01:14:19 EDT 2002 sparc64 unknown
	- Linux antarctica 2.4.19 #1 Tue Oct 29 21:33:52 EST 2002 i686 unknown
	- FreeBSD x-wing 4.6.2-RELEASE-p3 FreeBSD 4.6.2-RELEASE-p3 #1
	- SunOS access 4.1.4 1 sun4m
	- SunOS postal 5.8 Generic_108528-06 sun4u sparc SUNW,Ultra-1