C:套接字连接超时 [英] C: socket connection timeout

查看:189
本文介绍了C:套接字连接超时的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个简单的程序来检查如果一个端口是开放的,但我想缩短套接字连接上的超时长度,因为默认情况下是太长了。我不知道如何做到这一点,虽然。这里的code:

 的#include< SYS / socket.h中>
#包括LT&; SYS / time.h中>
#包括LT&; SYS / types.h中>
#包括LT&; ARPA / inet.h>
#包括LT&; netinet / in.h中>
#包括LT&;&errno.h中GT;
#包括LT&;&fcntl.h GT;
#包括LT&;&stdio.h中GT;
#包括LT&;&netdb.h中GT;
#包括LT&;&stdlib.h中GT;
#包括LT&;&string.h中GT;
#包括LT&;&unistd.h中GT;INT主(INT ARGC,字符** argv的){
    u_short口; / *用户指定的端口号* /
    字符地址[1023]。 / *将用u输入的地址副本* /
    结构sockaddr_in的地址; / * libc中的网络地址的数据结构* /
    短整型袜子= -1; / *为网络套接字文件描述符* /    如果(argc个!= 3){
        fprintf中(标准错误,用法%S< port_num><地址>,的argv [0]);
        返回EXIT_FAILURE;
    }    address.sin_addr.s_addr = inet_addr(的argv [2]); / *分配的地址* /
    address.sin_port = htons(与atoi(argv的[2])); / *翻译int2port NUM * /    袜子=插座(AF_INET,SOCK_STREAM,0);
    如果(连接(袜子,(结构sockaddr *)及地址的sizeof(地址))== 0){
        的printf(%i是开\\ n,口);
    }
    关闭(袜子);
    返回0;
}


解决方案

这文章可以帮助:<一href=\"http://developerweb.net/viewtopic.php?id=3196\">http://developerweb.net/viewtopic.php?id=3196 。看起来你把插座非阻塞模式,直到您已经连接,然后把它放回阻塞模式一旦连接的建立。

I have a simple program to check if a port is open, but I want to shorten the timeout length on the socket connection because the default is far too long. I'm not sure how to do this though. Here's the code:

#include <sys/socket.h>
#include <sys/time.h>
#include <sys/types.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <errno.h>
#include <fcntl.h>
#include <stdio.h>
#include <netdb.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>

int main(int argc, char **argv) {
    u_short port;                /* user specified port number */
    char addr[1023];             /* will be a copy of the address entered by u */
    struct sockaddr_in address;  /* the libc network address data structure */
    short int sock = -1;         /* file descriptor for the network socket */

    if (argc != 3) {
        fprintf(stderr, "Usage %s <port_num> <address>", argv[0]);
        return EXIT_FAILURE;
    }

    address.sin_addr.s_addr = inet_addr(argv[2]); /* assign the address */
    address.sin_port = htons(atoi(argv[2]));            /* translate int2port num */

    sock = socket(AF_INET, SOCK_STREAM, 0);
    if (connect(sock,(struct sockaddr *)&address,sizeof(address)) == 0) {
        printf("%i is open\n", port);
    }  
    close(sock);
    return 0;
}

解决方案

This article might help: http://developerweb.net/viewtopic.php?id=3196 . Looks like you put the socket into non-blocking mode until you've connected, and then put it back into blocking mode once the connection's established.

这篇关于C:套接字连接超时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆