Obtain the local IP address, mask, and gateway in Linux.

Source: Internet
Author: User
Obtain the local IP address, mask, and gateway in Linux.
 
 
1. Obtain the local IP address and mask /******************************** ************************************
* Function name: get_host_info
* Parameter Name: local_ip (out) IP
* Local_mask (out) mask
* Return value: 0 successfully
*-1 failed
* Function: Obtain the IP address and mask of the local machine.
**************************************** ****************************/
Int get_host_info (string & local_ip, string & local_mask)
{
Struct sockaddr_in * my_ip;
Struct sockaddr_in * ADDR;
Struct sockaddr_in myip;
My_ip = & myip;
Struct ifreq IFR;
Int sock;
If (sock = socket (af_inet, sock_dgram, 0) <0)
{
Return-1;
}
Strcpy (IFR. ifr_name, "eth0 ");
// Obtain the local IP Address
If (IOCTL (sock, siocgifaddr, & IFR) <0)
{
Return-1;
}
My_ip-> sin_addr = (struct sockaddr_in *) (& IFR. ifr_addr)-> sin_addr;
Local_ip = inet_ntoa (my_ip-> sin_addr );
 
// Obtain the local mask
If (IOCTL (sock, siocgifnetmask, & IFR) =-1 ){
Perror ("[-] IOCTL ");
Return-1;
}
ADDR = (struct sockaddr_in *) & (IFR. ifr_addr );
Local_mask = inet_ntoa (ADDR-> sin_addr );
Close (sock );
Return 0;
} 2. Retrieve the local gateway from the Internet. The error has been modified. # Define bufsize 8192 struct route_info {
U_int dstaddr;
U_int srcaddr;
U_int gateway;
Char ifname [if_namesize];
}; Int readnlsock (INT sockfd, char * bufptr, int seqnum, int PID)
{
Struct nlmsghdr * nlhdr;
Int readlen = 0, msglen = 0; do {
// Receives the kernel response
If (readlen = Recv (sockfd, bufptr, bufsize-msglen, 0) <0)
{
Perror ("Sock read :");
Return-1;
}

Nlhdr = (struct nlmsghdr *) bufptr; // check whether the header is valid
If (nlmsg_ OK (nlhdr, readlen) = 0) | (nlhdr-> nlmsg_type = nlmsg_error ))
{
Perror ("error in recieved packet ");
Return-1;
}

/* Check if the its last message */
If (nlhdr-> nlmsg_type = nlmsg_done)
{
Break;
}
Else
{
/* Else move the pointer to buffer appropriately */
Bufptr + = readlen;
Msglen + = readlen;
}

/* Check if its a multi part message */
If (nlhdr-> nlmsg_flags & nlm_f_multi) = 0)
{
/* Return if its not */
Break;
}
} While (nlhdr-> nlmsg_seq! = Seqnum) | (nlhdr-> nlmsg_pid! = PID ));
Return msglen;
} // Analyze the returned route information
Void parseroutes (struct nlmsghdr * nlhdr, struct route_info * rtinfo, char * gateway)
{
Struct rtmsg * rtmsg;
Struct rtattr * rtattr;
Int rtlen;
Char * tempbuf = NULL;
// 2007-12-10
Struct in_addr DST;
Struct in_addr gate;

Tempbuf = (char *) malloc (100 );
Rtmsg = (struct rtmsg *) nlmsg_data (nlhdr); // if the route is not for af_inet or does not belong to main routing table
// Then return.
If (rtmsg-> rtm_family! = Af_inet) | (rtmsg-> rtm_table! = Rt_table_main ))
Return;/* Get the rtattr field */
Rtattr = (struct rtattr *) rtm_rta (rtmsg );
Rtlen = rtm_payload (nlhdr );
For (; rta_ OK (rtattr, rtlen); rtattr = rta_next (rtattr, rtlen )){
Switch (rtattr-> rta_type ){
Case rta_oif:
If_indextoname (* (int *) rta_data (rtattr), rtinfo-> ifname );
Break;
Case rta_gateway:
Rtinfo-> gateway = * (u_int *) rta_data (rtattr );
Break;
Case rta_prefsrc:
Rtinfo-> srcaddr = * (u_int *) rta_data (rtattr );
Break;
Case rta_dst:
Rtinfo-> dstaddr = * (u_int *) rta_data (rtattr );
Break;
}
}
// 2007-12-10
DST. s_addr = rtinfo-> dstaddr;
If (strstr (char *) inet_ntoa (DST), "0.0.0.0 "))
{
Gate. s_addr = rtinfo-> gateway;
Sprintf (gateway, (char *) inet_ntoa (gate ));
}
Free (tempbuf );
Return;
}/************************************** ******************************
* Function name: get_gateway
* Parameter Name: Gateway (out) Gateway
* Return value: 0 successfully
*-1 failed
* Function: Obtain the gateway of the local machine.
**************************************** ****************************/
Int get_gateway (char * gateway)
{
Struct nlmsghdr * nlmsg;
Struct rtmsg * rtmsg;
Struct route_info * rtinfo;
Char msgbuf [bufsize];
 
Int sock, Len, msgseq = 0; // create a 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); For (; nlmsg_ OK (nlmsg, Len); nlmsg = nlmsg_next (nlmsg, Len )){
Memset (rtinfo, 0, sizeof (struct route_info ));
Parseroutes (nlmsg, rtinfo, Gateway );
}
Free (rtinfo );
Close (sock );
Return 0;
} Include all these header files. I didn't know which ones are useless, but I added them with no errors: # include <stdio. h>
# Include <string. h>
# Include <unistd. h>
# Include <net/If. h>
# Include <sys/IOCTL. h>
# Include <sys/types. h>
# Include <sys/socket. h>
# Include <netinet/in. h>
# Include <netdb. h>
# Include <ARPA/inet. h>
# Include <net/if_arp.h>
# Include <string> # include <ASM/types. h>
# Include <netinet/ether. h> # include <sys/IOCTL. h>
# Include <Linux/Netlink. h>
# Include <Linux/rtnetlink. h>
# Include <stdlib. h> If the string type is used, add: Using namespace STD; the above functions are compiled and run. Here, I will give you a memo, and I will give you convenience! Reference address: http://blog.chinaunix.net/u1/56834/showart.php? Id = 442919

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.