1. linux c code implementation
Copy codeThe Code is as follows: # 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.1 \ r \ nHost: www.ip138.com \ r \ nConnection: Close \ r \ n "};
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 );
// Obtain the IP address of www.ip138.com
Ptr = gethostbyname ("www.ip138.com ");
If (NULL = ptr ){
Perror ("gethostbyname error ");
Exit (0 );
}
// Try to connect each IP address of www.ip138.com until a connection is established successfully or the connection fails. 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: % s \ n", 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 that obtains the IP address to www.ip138.com
If (strlen (szBuffer )! = Send (sock, szBuffer, strlen (szBuffer), 0 )){
Perror ("send error ");
Exit (0 );
}
// Receive data packets
If (-1 = recv (sock, res, 1024,0 )){
Perror ("recv error ");
Exit (0 );
}
Printf ("res: \ n % s \ n", res );
Return 0;
}
2. Save the above Code to getip. c and compile it using the following command:Copy codeThe Code is as follows: gcc-o getip. c
3. Run the programCopy codeThe Code is as follows:./getip