#ifndef WIN32
#define WSACleanup(...)
#define SOCKET int
#define WSADATA int
void closesocket(int fd)
{
close(fd);
}
#endif
char* get_ip(char* hostname)
{
char* ip = NULL;
struct hostent *pHost = gethostbyname(hostname);
if(pHost)
{
if(pHost->h_addrtype == AF_INET)
{
while ( pHost->h_addr_list[0] )
{
struct in_addr *pAddr = (struct in_addr*)pHost->h_addr_list[0];
ip = inet_ntoa(*pAddr);
printf("ip:%s\n", ip);
break;
}
}
}
return ip;
}
int check_online(char* ip)
{SOCKET conn_sock;
struct sockaddr_in remote_addr;
WSADATA wsaData;
#ifdef WIN32
WSAStartup(MAKEWORD(1,1),&wsaData);//1.1版本
#endif
conn_sock = socket(AF_INET, SOCK_STREAM, 0);
remote_addr.sin_family = AF_INET;
remote_addr.sin_port = htons(80);
remote_addr.sin_addr.s_addr = inet_addr(ip);
printf("connect\n");
int ret = connect(conn_sock, (struct sockaddr *)&remote_addr, sizeof(struct sockaddr));
closesocket(conn_sock);
WSACleanup();
if(-1 == ret)
{
printf("offline\n");
return 0;
}
else
{
printf("online\n");
return 1;
}
return 0;
}
check_online(get_ip("www.baidu.com"));