获取指定网卡的网络信息

看了网络上的获取网络信息的脚本后,发现有些对我来说不好理解,于是做了一些改动,使之更简单:

注:网卡名称由调用者传入

#!/bin/sh
#***********************************************************************
#
# get-network
#
# Usage: get-network ifname
# 
#***********************************************************************

#get ifname from argument
case "$#" in
    1)
	IF="$1"
	;;
esac

if [ "$IF" = "" ]; then
	echo "Usage: get-network ifname"
	exit -1;
fi

#make sure interface $IF is up
interface=$(ifconfig | grep "$IF")
if [ "$interface" = "" ] ; then
	echo "interface $IF is down!!"
	exit -2;
fi

# get interface $IF ip
addr=$(ifconfig $IF | grep inet | awk '$1 == "inet" {print $2}')
mask=$(ifconfig &IF | grep inet | awk '$1 == "inet" {print $4}')
ip=$(echo "$addr" | cut -d: -f 2)
netmask=$(echo "$mask" | cut -d: -f 2)
echo "ip: $ip"
echo "netmask: $netmask"

 

很遗憾,这里只获取到ip和掩码信息,至于网关信息和dns信息,有兴趣的朋友可以自己尝试

dns: /etc/resolv.conf

route:route命令或者 /proc/net/route

在Java中,获取指定网卡的IP地址(inet地址)可以通过使用`java.net.NetworkInterface`类来实现。这个类代表了网络接口,包括物理网卡和虚拟网卡。以下是一个简单的示例代码,展示了如何获取指定网卡的IP地址: ```java import java.net.InetAddress; import java.net.NetworkInterface; import java.util.Enumeration; public class NetworkInterfaceExample { public static void main(String[] args) { try { // 获取系统所有的网络接口 Enumeration<NetworkInterface> networkInterfaces = NetworkInterface.getNetworkInterfaces(); while (networkInterfaces.hasMoreElements()) { NetworkInterface netInterface = networkInterfaces.nextElement(); // 过滤指定网络接口名称,例如 "eth0" if (netInterface.getName().equals("指定网卡名称")) { // 获取接口的所有inet地址 Enumeration<InetAddress> inetAddresses = netInterface.getInetAddresses(); while (inetAddresses.hasMoreElements()) { InetAddress inetAddress = inetAddresses.nextElement(); // 打印出网络接口的IP地址 System.out.println("IP Address for " + netInterface.getDisplayName() + " : " + inetAddress.getHostAddress()); } } } } catch (Exception e) { e.printStackTrace(); } } } ``` 在上面的代码中,首先我们获取了系统中所有的网络接口,然后遍历这些接口。对于每个接口,我们检查其名称是否是我们想要查询的网卡名称(例如:"eth0")。如果是,那么我们进一步获取网络接口的所有IP地址,并打印出来。 需要注意的是,网络接口的名称通常依赖于操作系统和网络配置。在Linux系统中,网络接口名称可能是像"eth0"、"eth1"这样的字符串,而在Windows系统中可能是像"Local Area Connection"这样的描述性字符串。 在实际使用中,你需要根据你的操作系统和具体需求来确定要查询的网卡名称。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值