/*
* getip.c
*
* Created on: 2013-7-11
* Author: Administrator
*/
#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 / HTTP/1.1\r\nUser-Agent: curl/7.19.7 (i486-pc-linux-gnu) libcurl/7.19.7 OpenSSL/0.9.8k zlib/1.2.3.3 libidn/1.15\r\nHost: ifconfig.me\r\nAccept: */*\r\n\r\n" };
char res[1024] = {0};
//初始化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);
//首先是获取www.ip138.com的IP地址http://city.ip138.com/ip2city.asp
//ptr = gethostbyname("www.ip138.com");
ptr = gethostbyname("ifconfig.me");
if (NULL == ptr) {
perror("gethostbyname error");
exit(0);
}
//对于www.ip138.com的每个IP进行尝试连接,直到有一个连接成功为止,或者无法连接,则退出程序
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");
}
//发送获取IP的数据包给www.ip138.com
if (strlen(szBuffer) != send(sock, szBuffer, strlen(szBuffer), 0)) {
perror("send error");
exit(0);
}
//接收数据包
if (-1 == recv(sock, res, 1024, 0)) {
perror("recv error");
exit(0);
}
printf("res:\n%s\n", res);
return 0;
}
函数执行的结果:
root@hj-desktop:/mnt/hgfs/share/program_test/testgetip# ./getip2
addr:133.242.129.236
res:
HTTP/1.1 200 OK
Date: Fri, 12 Jul 2013 07:56:38 GMT
Server: Apache
Vary: xxxxxxxxxxxxxxx
Connection: close
Transfer-Encoding: chunked
Content-Type: text/plain
d
112.4.139.21
0