Tuesday, June 23, 2009

getting gateway address

getGW()
{
struct nlmsghdr *nlMsg;
struct rtmsg *rtMsg;
struct route_info *rtInfo;
char msgBuf[BUFSIZE];
char mobileIp[20];
int sock, len, msgSeq = 0;
char buff[1024];

if((sock = socket(PF_NETLINK, SOCK_DGRAM, NETLINK_ROUTE)) < 0)
perror("Socket Creation: ");

memset(msgBuf, 0, BUFSIZE);
nlMsg = (struct nlmsghdr *)msgBuf;
rtMsg = (struct rtmsg *)NLMSG_DATA(nlMsg);
nlMsg->nlmsg_len = NLMSG_LENGTH(sizeof(struct rtmsg)); // Length of message.
nlMsg->nlmsg_type = RTM_GETROUTE; // Get the routes from kernel routing table .

nlMsg->nlmsg_flags = NLM_F_DUMP | NLM_F_REQUEST; // The message is a request for dump.
nlMsg->nlmsg_seq = msgSeq++; // Sequence of the message packet.
nlMsg->nlmsg_pid = getpid(); // PID of process sending the request.

if(send(sock, nlMsg, nlMsg->nlmsg_len, 0) < 0)
{
printf("Write To Socket Failed...\n");
return -1;
}

if((len = readNlSock(sock, msgBuf, msgSeq, getpid())) < 0)
{
printf("Read From Socket Failed...\n");
return -1;
}
rtInfo = (struct route_info *)malloc(sizeof(struct route_info));
for(;NLMSG_OK(nlMsg,len);nlMsg = NLMSG_NEXT(nlMsg,len))
{
memset(rtInfo, 0, sizeof(struct route_info));
parseRoutes(nlMsg, rtInfo);

}
free(rtInfo);
close(sock);

// printf("%s\n",gateway);
}

No comments: