写个函数,通过TCP握手的时间来测到端口的延迟,遇到有关问题,蛋疼
写个函数,通过TCP握手的时间来测到端口的延迟,遇到问题,蛋疼
我参考 http://blog.netzhou.net/?p=164 写的
结果如下图
测 8.8.8.8 53 的延迟正常
但是测任意IP的80端口都是connect()瞬间返回连接成功、select()瞬间返回可写。。。
最后那个9.X.X.X 是个不存在的IP,8.8.8.8也没开80端口,怎么都返回连接成功啊??
附上代码:
我参考 http://blog.netzhou.net/?p=164 写的
结果如下图
测 8.8.8.8 53 的延迟正常
但是测任意IP的80端口都是connect()瞬间返回连接成功、select()瞬间返回可写。。。
最后那个9.X.X.X 是个不存在的IP,8.8.8.8也没开80端口,怎么都返回连接成功啊??
附上代码:
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
#include <sys/time.h>
#include <stdio.h>
static double mytime(void)
{
struct timeval tv;
if (gettimeofday(&tv, NULL) == -1)
return 0.0;
return (double)tv.tv_usec + (double)tv.tv_sec * 1000000;
}
static double tcpping(char *host , int port ,int timeout )
{
struct sockaddr_in addr;
struct hostent *hp;
double time;
int fd;
if ((fd = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
return -10.0;
}
bzero((char *)&addr, sizeof(addr));
if ((hp = gethostbyname(host)) == NULL) {
return -10.0;
}
bcopy(hp->h_addr, &addr.sin_addr, hp->h_length);
addr.sin_family = AF_INET;
addr.sin_port = htons(port);
struct timeval tv;
tv.tv_sec = 0;
tv.tv_usec = timeout ;
double stime = mytime();
if (connect(fd, (struct sockaddr*)&addr, sizeof(addr)) < 0) {
return -1.0;
}
fd_set read, write;
FD_ZERO(&read);
FD_ZERO(&write);
FD_SET(fd, &read);
FD_SET(fd, &write);
if (select(fd + 1, &read, &write, NULL, &tv) == 0) {
close(fd);
return -2.0;
}
double etime = mytime();
time = etime - stime;
if (!FD_ISSET(fd, &read) && !FD_ISSET(fd, &write)) {
close(fd);
return -3.0;
}
close(fd);
return (time/1000);
}
int main(int argc,char *args[])
{
int count =0;