将端口号绑定到 TCP 套接字(outgoin)以发送数据包

2022-01-19 00:00:00 networking tcp c network-programming c++

我知道将端口号绑定到 TCP 套接字 来发送数据并不容易(因为系统通常将随机端口绑定到套接字).

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 bind a random port to sockets).

但我在一篇文章中读到,通过使用一些低级网络方法,您可以将端口号绑定到 TCP 套接字,然后使用它来发送数据?

But I read on one article that by using some low level networking methods you can bind a port number to a TCP socket then use it to send data ?

有没有人知道如何做到这一点?

Does anyone has an idea about how that could be done ?

我正在使用c编程语言

推荐答案

连接前绑定.

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

相关文章