binding a port number to a TCP socket (outgoin) to send packets

前端 未结 3 1171
被撕碎了的回忆
被撕碎了的回忆 2021-01-14 05:22

I know that it is not easy to bind a port number to TCP socket that you would use to send data (because systems usually bi

3条回答
  •  既然无缘
    2021-01-14 05:53

    Bind it before connecting.

    s = socket(AF_INET, SOCK_STREAM, 0);
    /* ... */
    
    memset(&client_addr, 0, sizeof(client_addr));
    client_addr.sin_family = AF_INET;
    client_addr.sin_port = htons(22222);
    
    if (bind(s, (struct sockaddr *) &client_addr, sizeof(client_addr)) < 0) {
        perror("bind");
        exit(1);
    }
    
    connect(s, (struct sockaddr *) &server_addr, sizeof(server_addr));
    

提交回复
热议问题