1. 程式人生 > >linux下 取得本機ip、掩碼、閘道器

linux下 取得本機ip、掩碼、閘道器

 //建立 Socket
 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;
 rtMsg = (struct rtmsg *)NLMSG_DATA(nlMsg);
 
 /* Fill in the nlmsg header*/
 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.
 
 /* Send the request */
 if(send(sock, nlMsg, nlMsg->nlmsg_len, 0) < 0){
  printf("Write To Socket Failed.../n");
  return -1;
 }
 
 /* Read the response */
 if((len = readNlSock(sock, msgBuf, msgSeq, getpid())) < 0) {
  printf("Read From Socket Failed.../n");
  return -1;
 }
 /* Parse and print the response */
 rtInfo = (struct route_info *)malloc(sizeof(struct route_info));