1, Linux C code implementation
Copy Code code 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\r\n"};
Char res[1024];
Initialize 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 the www.ip138.com
ptr = gethostbyname ("www.ip138.com");
if (NULL = = ptr) {
Perror ("gethostbyname error");
Exit (0);
}
To try the connection for each IP of the www.ip138.com until one of the connections is successful or cannot connect, 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 a packet to get IP to www.ip138.com
if (strlen (szbuffer)!= Send (Sock,szbuffer,strlen (szbuffer), 0)) {
Perror ("Send Error");
Exit (0);
}
Receive 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 GETIP.C, and use the following command to compile
Copy Code code as follows:
3. Run the program
Copy Code code as follows: