Chinaunix首页 | 论坛 | 博客
  • 博客访问: 584731
  • 博文数量: 141
  • 博客积分: 3425
  • 博客等级: 中校
  • 技术积分: 1609
  • 用 户 组: 普通用户
  • 注册时间: 2007-03-23 15:55
文章分类

全部博文(141)

文章存档

2019年(5)

2011年(19)

2010年(36)

2009年(13)

2008年(50)

2007年(18)

分类: C/C++

2010-10-28 11:55:22

static int Tcp1SocketCollectdata(unsigned char * cmd, int cmd_len,
                                 unsigned char * data, int data_len)
{
    int sock;
    struct sockaddr_in server;
    int received = 0;
    
    /* Create the TCP socket */
    if((sock = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP)) < 0)
    {
        printf("Tcp1SocketCollectdata create socket failed!\n");
        return 0;
    }
    struct timeval tv;
    tv.tv_sec = 3; /* 3 Secs Timeout */
    tv.tv_usec = 0; // Not init'ing this can cause strange errors

    setsockopt(sock, SOL_SOCKET, SO_RCVTIMEO, (char *)&tv, sizeof(struct timeval));
    /* Construct the server sockaddr_in structure */
    memset(&server, 0, sizeof(server)); /* Clear struct */
    server.sin_family = AF_INET; /* Internet/IP */
    server.sin_addr.s_addr = inet_addr("192.168.0.2"); /* IP address */
    server.sin_port = htons(6666); /* server port */
    /* Establish connection */
    if(connect(sock,
                (struct sockaddr *) &server,
                sizeof(server)) < 0)
    {
        printf("Tcp1SocketCollectdata connect socket failed!\n");

        close(sock);
        return 0;
    }
    if(send(sock, cmd, cmd_len, 0) != cmd_len) {
        printf("Tcp1SocketCollectdata sent cmd failed!\n");

        close(sock);
        return 0;
    }
    if((received = recv(sock, data, data_len, 0)) < 1) {
        printf("Tcp1SocketCollectdata receive failed!\n");
        close(sock);

        return 0;
    }
    // 校验
    printf("Tcp1SocketCollectdata received %d bytes\n", received);
    close(sock);

    return 0;
}


阅读(890) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~