首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C语言 >

写个函数,通过TCP握手的时间来测到端口的延迟,遇到有关问题,蛋疼

2013-02-27 
写个函数,通过TCP握手的时间来测到端口的延迟,遇到问题,蛋疼我参考http://blog.netzhou.net/?p164写的结

写个函数,通过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端口,怎么都返回连接成功啊??

写个函数,通过TCP握手的时间来测到端口的延迟,遇到有关问题,蛋疼


附上代码:


#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;


    char *s = args[1];
    int p = 80;
    if(argc == 3)
         p = atoi(args[2]);
    while (count < 3)
    {
        count ++;
        printf("%f \n",tcpping(s,p,1000));
    }
    return 0;
}

tcp Linux
[解决办法]
参考ping源代码。
[解决办法]
非阻塞connect失败也是返回可写可读的,需要使用int ret= getsockopt(SOL_SOCKET, SO_ERROR, &error, sizeof(error)),判断ret!=-1并且error==0才是连接成功。

热点排行
Bad Request.