daisy
daisy

Reputation: 23489

Linux C: How to know the default interface for internet access?

I want to find out the default network in use. My current method was to find all IP addresses and compare it to the default gateway IP address, but that sounds silly. What is the correct way of doing it ?

UPDATE

I want to use a C program, not by commands ...

Upvotes: 3

Views: 2504

Answers (1)

cnicutar
cnicutar

Reputation: 182609

You can try a slightly dirtier but infinitely easier approach:

cnicutar@lemon:~$ ip route show to 0.0.0.0/0
default via X.Y.Z.T dev eth0  proto static
                        ^^^^

So you can try:

FILE *cmd = popen("ip route show", "r");
fgets(str, LEN, cmd);

Then you can use strtok, strstr etc.

Upvotes: 4

Related Questions