• linux网络编程系列-网络连接的建立


    一个比较实用的连接函数,支持host为域名。

    #include <netdb.h>
    #include <sys/socket.h>
    #include <sys/types.h>
    #include <unistd.h>
    #include <fcntl.h>
    #include <arpa/inet.h>
    #include <netinet/tcp.h>
    
    #include <iostream>
    using namespace std;
    int my_connect(const char *host, int port)
    {
        char buf[1024];
        struct hostent he, *p; 
        struct sockaddr_in sin;
        socklen_t len = 0;
        int sock = -1, ret = 0, err = 0, flags = 0, on = 1;
        struct timeval t;
    
        assert(host != NULL);
    
        // invalid server
        if (host[0] == 0 || port <= 0 || port > 65535) {
            cout << "find invalid host " << host << " or port " << port << endl;
            return -1; 
        }
        //socket
        if ((sock = socket(PF_INET, SOCK_STREAM, 0)) < 0) {
            cout << "cannot create socket while connecting to "
                << host << ":" << port << endl;
            return -1;
        }
    
        //connect
        bzero(&sin, sizeof(sin));
        sin.sin_addr.s_addr = inet_addr(host);
        if ((sin.sin_addr.s_addr) == INADDR_NONE) { /* host is not numbers-and-dots ip address */
            ret = gethostbyname_r(host, &he, buf, sizeof(buf), &p, &err);
            if (ret < 0 || err != 0 || p == NULL) {
                        cout << "cannot resolve hostname while connecting to "
                            << host << ":" << port << endl;
                close(sock);
                return -1;
            }
            memcpy(&sin.sin_addr.s_addr, he.h_addr, sizeof(sin.sin_addr.s_addr));
        }
        sin.sin_family = AF_INET;
        sin.sin_port = htons(port);
    
        flags = fcntl(sock, F_GETFL, 0);
        fcntl(sock, F_SETFL, flags | O_NONBLOCK);
        setsockopt(sock, IPPROTO_TCP, TCP_NODELAY, &on, sizeof(on));
        ret = connect(sock, (struct sockaddr *) &sin, sizeof(sin));
        if (ret == 0) {
            fcntl(sock, F_SETFL, flags);
            cout << "connect to " << host << ":" << port << "OK" << endl;
            return sock;
        }
        close(sock);
        return -1;
    }


  • 相关阅读:
    小白学开发(iOS)OC_ 使用继承来扩充类(2015-08-07)
    UI组件之TextView及其子类(三)ToggleButton和Switch
    C++智能指针--shared_ptr
    HDU 1013 Digital Roots 题解
    对touch事件传递的简单理解
    【LeetCode-面试算法经典-Java实现】【096-Unique Binary Search Trees(唯一二叉搜索树)】
    Cocos2d-x 坐标系
    hdu1518 Square
    servlet3.0新特性
    OGNL表达式
  • 原文地址:https://www.cnblogs.com/whuqin/p/4982000.html
Copyright © 2020-2023  润新知