Java Reference
In-Depth Information
that particular network interface. For example, this code fragment attempts to find the
primary Ethernet interface on a Unix system:
try
{
NetworkInterface
ni
=
NetworkInterface
.
getByName
(
"eth0"
);
if
(
ni
==
null
)
{
System
.
err
.
println
(
"No such interface: eth0"
);
}
}
catch
(
SocketException
ex
)
{
System
.
err
.
println
(
"Could not list sockets."
);
}
public static NetworkInterface getByInetAddress(InetAddress address) throws SocketException
The
getByInetAddress()
method returns a
NetworkInterface
object representing the
network interface bound to the specified IP address. If no network interface is bound
to that IP address on the local host, it returns null. If anything goes wrong, it throws a
SocketException
. For example, this code fragment finds the network interface for the
local loopback address:
try
{
InetAddress
local
=
InetAddress
.
getByName
(
"127.0.0.1"
);
NetworkInterface
ni
=
NetworkInterface
.
getByInetAddress
(
local
);
if
(
ni
==
null
)
{
System
.
err
.
println
(
"That's weird. No local loopback address."
);
}
}
catch
(
SocketException
ex
)
{
System
.
err
.
println
(
"Could not list network interfaces."
);
}
catch
(
UnknownHostException
ex
)
{
System
.
err
.
println
(
"That's weird. Could not lookup 127.0.0.1."
);
}
public static Enumeration getNetworkInterfaces() throws SocketException
The
getNetworkInterfaces()
method returns a
java.util.Enumeration
listing all the
network interfaces on the local host.
Example 4-8
is a simple program to list all network
interfaces on the local host:
Example 4-8. A program that lists all the network interfaces
import
java.net.*
;
import
java.util.*
;
public
class
InterfaceLister
{
public
static
void
main
(
String
[]
args
)
throws
SocketException
{
Enumeration
<
NetworkInterface
>
interfaces
=
NetworkInterface
.
getNetwork
Interfaces
();
while
(
interfaces
.
hasMoreElements
())
{
NetworkInterface
ni
=
interfaces
.
nextElement
();
System
.
out
.
println
(
ni
);
}