linux 读取 gateway ip socket,linux下获取网口ip、netmask、gateway

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;

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值