open "/proc/net/route" then parse content
$ cat /proc/net/routeIface Destination Gateway Flags RefCnt Use Metric Mask MTU Window IRTTeth1 0000A8C0 00000000 0001 0 0 0 00FFFFFF 0 0 0eth0 005111AC 00000000 0001 0 0 1 00FFFFFF 0 0 0eth1 0000FEA9 00000000 0001 0 0 1000 0000FFFF 0 0 0eth0 00000000 FE5111AC 0003 0 0 0 00000000 0 0 0
00000000 is default interface
Then get this interface ip address.
Using getsockname with an external connection
new connection outside then use this socket value to check own ip address.
/*
* Find local ip used as source ip in ip packets.
* Use getsockname and a udp connection
*/
#include<stdio.h> //printf
#include<string.h> //memset
#include<errno.h> //errno
#include<sys/socket.h> //socket
#include<netinet/in.h> //sockaddr_in
#include<arpa/inet.h> //getsockname
#include<unistd.h> //close
int
main (
int
argc ,
char
*argv[] )
{
const
char
* google_dns_server =
"8.8.8.8"
;
int
dns_port = 53;
struct
sockaddr_in serv;
int
sock = socket ( AF_INET, SOCK_DGRAM, 0);
//Socket could not be created
if
(sock < 0)
{
perror
(
"Socket error"
);
}
memset
( &serv, 0,
sizeof
(serv) );
serv.sin_family = AF_INET;
serv.sin_addr.s_addr = inet_addr( google_dns_server );
serv.sin_port = htons( dns_port );
int
err = connect( sock , (
const
struct
sockaddr*) &serv ,
sizeof
(serv) );
struct
sockaddr_in name;
socklen_t namelen =
sizeof
(name);
err = getsockname(sock, (
struct
sockaddr*) &name, &namelen);
char
buffer[100];
const
char
* p = inet_ntop(AF_INET, &name.sin_addr, buffer, 100);
if
(p != NULL)
{
printf
(
"Local ip is : %s \n"
, buffer);
}
else
{
//Some error
printf
(
"Error number : %d . Error message : %s \n"
,
errno
,
strerror
(
errno
));
}
close(sock);
return
0;
}
沒有留言:
張貼留言