close(sock);
return -1;
}
memcpy(&sin, &ifr.ifr_addr, sizeof(sin));
char *ip_get = inet_ntoa(sin.sin_addr);
strncpy(ip, ip_get, strlen(ip_get));
if (ioctl(sock, SIOCGIFNETMASK, &ifr) < 0)
{
close(sock);
return -1;
}
memcpy(&sin, &ifr.ifr_addr, sizeof(sin));
char *mask_get = inet_ntoa(sin.sin_addr);
strncpy(mask, mask_get, strlen(mask_get));
close(sock);
return 0;
}
/********************************************************************
* get_gateway: get the gateway, specify eth name
*
* eth_name: eth name, not null
* gateway: gateway, not null
*
* return: 0 succ
* -1 fail
********************************************************************/
int get_gateway(const char *eth_name, char *gateway)
{
int ret = -1;
if (eth_name == NULL || gateway == NULL)
{
return ret;
}
struct nlmsghdr *nlMsg;
struct route_info *rtInfo;
char msgBuf[BUFSIZE];
int sock, len, msgSeq = 0;
if((sock = socket(PF_NETLINK, SOCK_DGRAM, NETLINK_ROUTE)) < 0)
{
//perror("Socket Creation: ");
return -1;
}
//Initialize the buffer
memset(msgBuf, 0, BUFSIZE);
//point the header and the msg structure pointers into the buffer
nlMsg = (struct nlmsghdr *)msgBuf;
nlMsg->nlmsg_len = NLMSG_LENGTH(sizeof(struct rtmsg));
nlMsg->nlmsg_type = RTM_GETROUTE;
nlMsg->nlmsg_flags = NLM_F_DUMP | NLM_F_REQUEST;
nlMsg->nlmsg_seq = msgSeq++;
nlMsg->nlmsg_pid = getpid();
//Send the request
if (send(sock, nlMsg, nlMsg->nlmsg_len, 0) < 0){
close(sock);
return ret;
}
//Read the response
if((len = read_nlSock(sock, msgBuf, msgSeq, getpid())) < 0) {
//printf("Read From Socket Failed.../n");
close(sock);
return ret;
}
//Parse and print the response
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));
if (parse_routes(nlMsg, rtInfo, eth_name, gateway) == 0)
{
ret = 0;
break;
}
}
free(rtInfo);
close(sock);
return 0;
}
int main(int argc, char **argv)
{
if (argc != 2)
{
printf("usage:program \n");
exit(0);
}
char ip[20];
char mask[20];
char gateway[20];
memset(ip, 0, 20);
memset(mask, 0, 20);
memset(gateway, 0, 20);
get_ip_mask(argv[1], ip, mask);
get_gateway(argv[1], gateway);
printf("ip:%s\n", ip);
printf("mask:%s\n", mask);
printf("gateway:%s\n", gateway);
return 0;
}