IOCTL get native network card IP address | Socket () Copy code

Source: Internet
Author: User
Tags new set
<span style= "font-family:arial, Helvetica, Sans-serif; Background-color:rgb (255, 255, 255); ></span><pre name= "code" class= "CPP" > #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 for interface to name

    strcpy (ifr.ifr_name, "eth1");

    The SIOCGIFADDR flag represents obtaining the interface address

    if (IOCTL (Inet_sock, siocgifaddr, &ifr) = =  0)  
        perror ("IOCTL");

    printf ("%s\n", Inet_ntoa ((struct sockaddr_in*) & (IFR.IFR_ADDR)) (->SIN_ADDR)); Convert to dotted decimal format return
    0;
<span style= "font-family:arial, Helvetica, Sans-serif; Background-color:rgb (255, 255, 255); >----------------------------------------------------------------------------------------------------------- ---------------------------------------------------</span>

The IFREQ structure is defined in/usr/include/net/if.h, used to configure IP addresses, activate interfaces, and configure interface information such as MTU.
It contains the name and content of an interface-(a common body, possibly an IP address, broadcast address, subnet mask, mac number, MTU, or other content).
The ifreq is included in the ifconf structure. The ifconf structure is usually used to hold information about all interfaces.

--------------------------------------------------------------------------------------------------------------- -----------------------------------------------

Using IOCTL to obtain a local IP address uses two structural ifconf and Ifreq, which for most people
Is relatively unfamiliar, here to give you a relatively simple way of understanding, of course, only a help
The method of understanding, in the description may have some place and the real definition has the discrepancy, only for reference.

First get to know ifconf and Ifreq:

Ifconf is usually used to hold all interface information.
If.h
{
    int    Ifc_len;            /* Size of buffer    * *
    
    {
        char *ifcu_buf;                        /* Input from user->kernel*/
        struct Ifreq *ifcu_req;        /* Return from kernel->user*/
    } IFC_IFCU;
};
#define    ifc_buf    ifc_ifcu.ifcu_buf/        * Buffer Address    * *
#define    ifc_req    ifc_ifcu.ifcu_req/        * array of Structures    * *
Ifreq the information used to hold an interface
If.h
struct Ifreq {
    Char Ifr_name[ifnamsiz];
    Union {
        struct SOCKADDR ifru_addr;
        struct SOCKADDR ifru_dstaddr;
        struct SOCKADDR ifru_broadaddr;
        Short ifru_flags;
        int ifru_metric;
        caddr_t Ifru_data;
    } Ifr_ifru;
};
#define IFR_ADDR IFR_IFRU.IFRU_ADDR
#define IFR_DSTADDR IFR_IFRU.IFRU_DSTADDR
#define IFR_BROADADDR IFR_IFRU.IFRU_BROADADDR

The above two structures look more complicated, and we now simplify them a little:
For example, now we have the ability to achieve local IP.

Our approach is to:
1. Get the information of all the local interfaces through IOCTL and save them in ifconf
2. Remove the IP address information from each ifreq in the ifconf

When used specifically, we can assume that Ifconf has two members:
Ifc_len and Ifc_buf, as shown in Figure one:

Ifc_len: Represents the buffer length used to hold all interface information
Ifc_buf: A buffer that represents the information that holds the interface

So we need to initialize the ifconf ifc_led and Ifc_buf at the beginning of the program.
Next use IOCTL to get all the interface information, complete the total length of the information in the Ifc_len within the actual obtained excuse
And the information is stored in the ifc_buf.
The following diagram: (assuming that two interface information is read)


Next we just need to get the IP address information from one interface information.

Here's a simple reference:

#include in.h>
#include <string.h>
#include if.h>
int main ()
{
    int i=0;
    int sockfd;
  struct ifconf ifconf;
  unsigned char buf[512];
  struct Ifreq *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);    Get all interface information
  
  Next one gets the IP address
  Ifreq = (struct ifreq*) buf;  
  For (i= (ifconf.ifc_len/sizeof (struct ifreq)); i>0; i--)
  {
      if (ifreq->ifr_flags = = af_inet) {            //for IPv4
          printf ("name = [%s]\n", ifreq->ifr_name);
      
                      Inet_ntoa ((struct sockaddr_in*) & (IFREQ->IFR_ADDR)) (->SIN_ADDR));
      ifreq++;
//  }
  }
    return 0;
}
This method is for informational purposes only and is also useful for obtaining additional information.

--------------------------------------------------------------------------------------------------------------- -----------------------------------------------Brief:
Creates a set of interfaces.
#include <winsock.h>
Socket PASCAL FAR socket (int af, int type, int protocol);
AF: An address description. Currently only supports af_inet format, that is, the ARPA Internet address format.
Type: A description of the types of the new set of interfaces.
Protocol: The protocol used by the socket interface. If the caller does not want to specify, use 0.
Notes
   Socket() function is used to assign the descriptor of a set of interfaces and the resources it uses based on the specified address family, data type, and protocol. If the protocol protocol is not specified (equal to 0), the default connection method is used.
Only one protocol is supported for a particular set of interfaces that use a given address family. However, the address family can be set to Af_unspec (unspecified), so that the protocol parameters are specified. The protocol number is specific to the communication domain in which the communication is made. The following types of descriptions are supported:
Type explanation
Sock_stream provides an orderly, reliable, two-way, and concatenated byte stream, using Out-of-band data transfer mechanisms to use TCP for Internet address families.
Sock_dgram supports connectionless, unreliable, datagram services that use a fixed size (usually small) buffer for use with UDP for Internet address families.
The Sock_stream type of socket is a full two-way byte stream. For a Stream class sleeve interface, you must be in a connected state before you receive or send data. Use Connect () call to establish a connection with another set of interfaces, after the successful connection, you can use Send () and recv () to transfer data. When the session is finished, call Closesocket (). Out-of-band data is received by Send () and recv () as required.
The communication protocol that implements the Sock_stream type sleeve interface guarantees that the data will not be lost or duplicated. If the terminal protocol has buffer space and the data cannot be sent successfully at a certain time, the connection is considered interrupted and subsequent calls are returned with a wsaetimeout error.
The SOCK_DGRAM type socket interface allows datagrams to be sent or received from any port using SendTo () and Recvfrom (). If such a set of interfaces is connected with a specified port with connect (), then send () and recv () are sent and received with the port for datagram.
return value
If no error occurs, the socket () returns a descriptive word that references the new set of interfaces. Otherwise, the Invaid_socket error is returned, and the application can obtain the appropriate error code by WSAGetLastError ().
Error code:
Wsanotinitialised: You should first successfully invoke WSAStartup () before using this API.
The Wsaenetdown:windows sleeve interface implementation detects the failure of the network sub system.
Wsaeafnosupport: The specified address family is not supported.
Wsaeinprogress: A blocked Windows Socket interface call is running.
Wsaemfile: No file descriptors available.
WSAENOBUFS: No buffer available, unable to create socket interface.
Wsaeprotonosupport: The specified protocol is not supported.
Wsaeprototype: The specified protocol does not apply to this set of interfaces.
Wsaesocktnosupport: This type of socket interface is not supported in this address family.
See
Accept (), bind (), connect (), getsockname (), getsockopt (), setsockopt (), listen (), recv (), Recvfrom (), select (), send (), S EndTo (), Shutdown (), ioctlsocket (). 4.2 Database Routines
Socket ()
Function Prototypes:
Socket WSAAPI Socket (
int AF,
int type,
int protocol
);
The function and parameter definitions are included in the Winsock2.h header file, and no specific parameters are found in MSDN.
Parameter options and Definitions:
Address Family AF: (Common Af_inet Implementation TCP/UDP protocol)
#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/* CCITT protocols, X.25 etc * *
#define AF_SNA/* IBM SNA/*
#define AF_DECNET/* DECnet * *
#define AF_DLI/* Direct Data Link Interface * * #define AF_LAT/* LAT * *
#define AF_HYLINK/* NSC Hyperchannel * *
#define AF_APPLETALK/* APPLETALK * *
#define AF_NETBIOS/* Netbios-style addresses * *
#define AF_VOICEVIEW/* VoiceView * *
#define AF_FIREFOX/* Protocols from FIREFOX * *
#define AF_UNKNOWN1/* Somebody is using this! */
#define AF_BAN/* Banyan * *
#define AF_ATM/* Native ATM Services * *
#define AF_INET6/* Internetwork Version 6 * *
#define AF_CLUSTER/* Microsoft Wolfpack * *
#define AF_12844/* IEEE 1284.4 WG AF */
Socket Type:
#define SOCK_STREAM 1/* STREAM socket */
#define SOCK_DGRAM 2/* Datagram Socket * *
#define SOCK_RAW 3/* Raw-protocol interface * *
#define SOCK_RDM 4/* reliably-delivered message * *
#define SOCK_SEQPACKET 5/* Sequenced Packet stream * *
Protocol type Protocol:
#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/* PUP * *
#define IPPROTO_UDP/* User Datagram Protocol * *
#define IPPROTO_IDP/* XNS IDP * *
#define IPPROTO_ND/* 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.