Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I fetch the ethernet port given the ip address?

I am trying to write a bash script to fetch the ethernet port of an interface whose IP address I know. I need to grab this from ifconfig but can't seem to be able to figure out how to go about it. Any ideas?

Thanks.

like image 813
fzkl Avatar asked Feb 13 '11 18:02

fzkl


People also ask

How do I find a device by IP address?

You can follow a path to a device if you know its IP address by using the tracert command at the command prompt (cmd). Open a Command Prompt window and type in tracert followed by the IP address that you know. The output will show each router that has a connection to that device will pass through.

How do I find the port number of a specific IP address?

How do I find the port number of a specific IP address? All you have to do is type “netstat -a” on Command Prompt and hit the Enter button. This will populate a list of your active TCP connections. The port numbers will be shown after the IP address and the two are separated by a colon.

How do I query an IP address NIC eth0?

You can use the ifconfig command or ip command with grep command and other filters to find out an IP address assigned to eth0 and display it on screen.


2 Answers

Replace 127.0.0.1 with the ip address you want to get the interface info for

ifconfig  | grep 127.0.0.1 -B1 | grep Link | cut -f 1 '-d '

If you also want to identify the physical port on the machine, run

ethtool -p $OUTPUT_OF_FIRST_COMMAND

It will blink the light on the ethernet card associated with that interface

like image 192
Nick Avatar answered Oct 13 '22 12:10

Nick


A little messy but should work:

/sbin/ifconfig | grep -B1 1.2.3.4 | awk '{print $1; exit}'

Optionally, you could use the ip command which, when used with the -o|-oneline option, is a lot easier to parse. For example

ip -o addr | awk '/1.2.3.4/{print $2}'
like image 42
Shawn Chin Avatar answered Oct 13 '22 12:10

Shawn Chin