IOCTL obtains the IP address of the local Nic | socket ()

Source: Internet
Author: User
# Include < String . H>
# Include <sys/socket. h>
# Include <sys/IOCTL. h>
# Include <net/ If . H>
# Include <stdio. h>
# Include <netinet/ In . H>
# Include <ARPA/inet. h>
Int Main ()
{
Int Inet_sock;
Struct Ifreq IFR;
Inet_sock = socket (af_inet, sock_dgram, 0 );
// Eth0 is the interface Name

Strcpy (IFR. ifr_name, " Eth1 " );

// The siocgifaddr flag indicates the interface address to be obtained.

If (IOCTL (inet_sock, siocgifaddr, & IFR) = 0 )
Perror ( " IOCTL " );

Printf ( " % S \ n " , Inet_ntoa ((( Struct Sockaddr_in *) & (IFR. ifr_addr)-> sin_addr ));
Return 0 ;
}

Certificate --------------------------------------------------------------------------------------------------------------------------------------------------------------

The ifreq structure is defined in/usr/include/NET/If. H. It is used to configure IP addresses, activate interfaces, configure MTU and other interface information.
It contains the name and specific content of an interface (it is a shared body, which may be an IP address, broadcast address, subnet mask, MAC Number, MTU or other content ).
Ifreq is included in the ifconf structure. The ifconf structure is usually used to save information of all interfaces.

Certificate --------------------------------------------------------------------------------------------------------------------------------------------------------------

When IOCTL is used to obtain the local IP address, two struct ifconf and ifreq are used.
These are all unfamiliar. Here is a simple way to understand, of course, just a help
There may be some differences between the description and the actual definition, which is for reference only.

First, let's get to know ifconf and ifreq:

 
// Ifconf is usually used to save all interface information
 
// If. h
 
StructIfconf
 
{
 
IntIfc_len;/* Size of buffer */
 
Union
{
 
Char* Ifcu_buf;/* Input from user-> kernel */
 
StructIfreq * ifcu_req;/* Return from kernel-> User */
 
} Ifc_ifcu;
 
};
 
# DefineIfc_buf ifc_ifcu.ifcu_buf/* Buffer address */
 
# DefineIfc_req ifc_ifcu.ifcu_req/* Array of structures */
 
 
 
// Ifreq is used to save the information of an interface.
 
// If. h
StructIfreq {
 
CharIfr_name [ifnamsiz];
 
Union {
 
StructSockaddr ifru_addr;
 
StructSockaddr ifru_dstaddr;
 
StructSockaddr ifru_broadaddr;
 
ShortIfru_flags;
 
IntIfru_metric;
 
Caddr_t ifru_data;
 
} Ifr_ifru;
 
};
 
# DefineIfr_addr ifr_ifru.ifru_addr
 
# DefineIfr_dstaddr ifr_ifru.ifru_dstaddr
# DefineIfr_broadaddr ifr_ifru.ifru_broadaddr

 

The above two structures seem complicated, so we can simplify them now:
For example, we want to implement the function of obtaining a local IP address.

Our practice is:
1. Obtain information about all local interfaces through IOCTL and save the information in ifconf.
2. Then retrieve the IP address information in each ifreq from ifconf.

For specific use, we can think that ifconf has two members:
Ifc_len and ifc_buf,1:

Ifc_len: indicates the buffer length used to store all interface information.
Ifc_buf: buffer zone for storing Interface Information

So we needProgramInitialize ifc_led and ifc_buf of ifconf at the beginning.
Next, use IOCTL to obtain information about all interfaces. Then, put the ifc_len memory into the total length of the provided information.
And the information is stored in ifc_buf.
As shown in: (assume that two interfaces are read)

 

Next, we only need to obtain IP address information from one interface.

The following is a simple reference:

 
# Include

  
 
# Include

  
 
# Include

  
 
# Include

  
 
# Include

  
   
In. h>

  
 
# Include <String. H>
 
# Include

  
   
If. h>

  
 
# Include

  
 
 
 
IntMain ()
 
{
 
IntI = 0;
 
IntSockfd;
StructIfconf;
 
UnsignedCharBuf [2, 512];
 
StructIfreq * ifreq;
 
 
 
// Initialize ifconf
 
Ifconf. ifc_len = 512;
 
Ifconf. ifc_buf = Buf;
 
 
 
If(Sockfd = socket (af_inet, sock_dgram, 0) <0)
 
{
 
Perror ("Socket");
 
Exit (1 );
 
}
 
IOCTL (sockfd, siocgifconf, & ifconf );// Obtain all interface information
 
 
// Obtain IP addresses one by one
 
Ifreq = (StructIfreq *) BUF;
 
For(I = (ifconf. ifc_len/Sizeof(StructIfreq); I> 0; I --)
 
{
 
// If (ifreq-> ifr_flags = af_inet) {// for IPv4
 
Printf ("Name = [% s] \ n", Ifreq-> ifr_name );
 
Printf ("Local ADDR = [% s] \ n",
 
Inet_ntoa (((StructSockaddr_in *) & (ifreq-> ifr_addr)-> sin_addr ));
 
Ifreq ++;
 
//}
}
 
Return0;
 
}
This method is for reference only and can be used to obtain other information.

Certificate --------------------------------------------------------------------------------------------------------------------------------------------------------------

Brief description:
Create a set of interfaces.
# Include <Winsock. h>
Socket Pascal far socket (int af, int type, int Protocol );
AF: An address description. Currently, only the af_inet format is supported, that is, the ARPA Internet address format.
Type: type description of the new interface.
Protocol: the protocol used by the set interface. If the caller does not want to specify the value, the value 0 is available.
Note

socket () the function is used to allocate a set of Interface Description words and resources based on the specified address family, data type, and protocol. If protocol is not specified (equal to 0), the default connection mode is used.
only one protocol is supported for a specific set of interfaces that use a given address family. However, the address family can be set to af_unspec (not specified), so that the protocol parameters will be specified. The Protocol Number is specific to the communication domain ". The following types are supported:
type description
sock_stream provides ordered, reliable, bidirectional, and connection-based byte streams. It uses the out-of-band data transmission mechanism, use TCP for the Internet address family.
sock_dgram supports connectionless, unreliable, and datagram services that use a fixed (usually very small) buffer, and uses UDP for Internet address families.
the sock_stream interface is a full bidirectional byte stream. For stream-type interfaces, they must be connected before receiving or sending data. Call connect () to establish a connection with another interface. After the connection is successful, send () and Recv () can be used to transmit data. When the session ends, closesocket () is called (). The out-of-band data is received by sending () and Recv () according to regulations.
the communication protocol implementing the sock_stream interface ensures that data is not lost or duplicated. If the terminal protocol has buffer space and data cannot be successfully sent within a certain period of time, the connection is considered to be interrupted and subsequent calls will also be returned with a wsaetimeout error.
the sock_dgram type interface allows sendto () and recvfrom () to send or receive data packets from any port. If such an interface is connected to a specified port using connect (), send () and Recv () can be used to send and receive data packets with this port.
return value

If no error occurs, socket () returns the description that references the new interface. Otherwise, an invaid_socket error is returned. The application can obtain the error through wsagetlasterror ().Code.
Error code:
Wsanotinitialised: before using this API, you must successfully call wsastartup ().
Wsaenetdown: A Windows interface is used to detect the failure of the network subsystem.
Wsaeafnosupport: the specified address family is not supported.
Wsaeinss SS: A blocked Windows interface call is running.
Wsaemfile: no description of an available file.
Wsaenobufs: no available buffer, and a set of interfaces cannot be created.
Wsaeprotonosupport: the specified protocol is not supported.
Wsaeprototype: the specified Protocol does not apply to this interface.
Wsaesocktnosupport: This type of interface is not supported in this address family.
See

Accept (), BIND (), connect (), getsockname (), getsockopt (), setsockopt (), listen (), Recv (), recvfrom (), select (), send (), sendto (), shutdown (), ioctlsocket (). 4.2 data library routine
Socket ()
Function prototype:
Socket wsaapi socket (
Int AF,
Int type,
Int Protocol
);
This function and Parameter definition are included in the winsock2.h header file and cannot be found in msdn.
Parameter options and definitions:
Address Family AF: (using af_inet for TCP/UDP)
# Define af_unspec 0/* unspecified */
# Define af_unix 1/* local to host (pipes, portals )*/
# Define af_inet 2/* Internetwork: UDP, TCP, etc .*/
# Define af_implink 3/* ARPANET imp addresses */
# Define af_pup 4/* pup protocols: e.g. BSP */
# Define af_chaos 5/* mit chaos protocols */
# Define af_ns 6/* Xerox NS protocols */
# Define af_ipx af_ns/* IPX protocols: IPX, SPX, etc .*/
# Define af_iso 7/* ISO protocols */
# Define af_osi af_iso/* OSI is ISO */
# Define af_ecma 8/* European Computer Manufacturers */
# Define af_datakit 9/* datakit protocols */
# Define af_ccitt 10/* CCITT protocols, X.25 etc */
# Define af_sna 11/* ibm sna */
# Define af_decnet 12/* decnet */
# Define af_dli 13/* Direct Data Link Interface */# define af_lat 14/* lat */
# Define af_hylink 15/* NSC hyperchannel */
# Define af_appletalk 16/* appletalk */
# Define af_netbios 17/* NetBIOS-style addresses */
# Define af_voiceview 18/* voiceview */
# Define af_firefox 19/* protocols from Firefox */
# Define af_unknown1 20/* somebody is using this! */
# Define af_ban 21/* Banyan */
# Define af_atm 22/* Native ATM services */
# Define af_inet6 23/* Internetwork version 6 */
# Define af_cluster 24/* Microsoft wolfpack */
# Define af_12844 25/* IEEE 1284.4 WG Af */
Socket Type:
# Define sock_stream 1/* stream socket */
# Define sock_dgram 2/* datatesocket */
# Define sock_raw 3/* Raw-Protocol Interface */
# Define sock_rdm 4/* reliably-delivered message */
# Define sock_seqpacket 5/* sequenced packet stream */
Protocol type:
# Define ipproto_ip 0/* dummy for IP */
# Define ipproto_icmp 1/* Control Message Protocol */
# Define ipproto_igmp 2/* Internet Group Management Protocol */
# Define ipproto_ggp 3/* gateway ^ 2 (Deprecated )*/
# Define ipproto_tcp 6/* tcp */
# Define ipproto_pup 12/* pup */
# Define ipproto_udp 17/* User datasync Protocol */
# Define ipproto_idp 22/* xns IDP */
# Define ipproto_nd 77/* Unofficial net disk proto */

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.