Linux c gets the implementation method of native public network IP

  • 2020-04-02 00:44:03
  • OfStack

1. Linux c code implementation

#include <netdb.h>
#include <stdio.h> 
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <sys/socket.h>
typedef enum {false,true}bool;
int main() 
{ 
    bool flag;
    int    sock;
    char **pptr = NULL;
    struct sockaddr_in    destAddr;
    struct hostent    *ptr = NULL;
    char destIP[128];
    char szBuffer[] = {"GET /ip2city.asp HTTP/1.1rnHost:www.ip138.comrnConnection:Closernrn"};
    char res[1024];

  //Initialize the socket
    sock = socket(AF_INET,SOCK_STREAM,0);
    if( -1 == sock ){
        perror("creat socket failed");
        exit(0);
    }

    bzero((void *)&destAddr,sizeof(destAddr));
    destAddr.sin_family = AF_INET;        
    destAddr.sin_port = htons(80);
   //The first is to get the IP address of www.ip138.com
    ptr = gethostbyname("www.ip138.com");
    if(NULL == ptr){
        perror("gethostbyname error");
        exit(0);
    }   
  //For each IP of www.ip138.com, try to connect until one of the connections succeeds or fails to connect, then exit the program
    for(flag=false,pptr=ptr->h_addr_list ; NULL != *pptr ; ++pptr){
        inet_ntop(ptr->h_addrtype,*pptr,destIP,sizeof(destIP));
        printf("addr:%sn",destIP);
        destAddr.sin_addr.s_addr = inet_addr(destIP);
        if(-1!=connect(sock,(struct sockaddr *)&destAddr,sizeof(struct sockaddr))){
            flag = true;
            break;
        }
    }

    if(false == flag){
        perror("connect failed");
    }

  //Send the packet to obtain IP to www.ip138.com
    if(strlen(szBuffer) != send(sock,szBuffer,strlen(szBuffer),0)){
        perror("send error");
        exit(0);
    }

  //Receiving packet
    if(-1 == recv(sock,res,1024,0)){
        perror("recv error");
        exit(0);
    }

    printf("res:n%sn",res);    
    return 0;
}

2. Save the above code to getip. C and compile it using the following command

gcc -o getip getip.c

3. Run the program

./getip

Related articles: