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

2019-02-18 12:41发布

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

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 ?

I am using c programming language

3条回答
成全新的幸福
2楼-- · 2019-02-18 12:51

Actually it is quite easy. Simply use the bind function as you would for a server.

查看更多
贼婆χ
3楼-- · 2019-02-18 12:59

You can simply call bind() before connect() in a client in the same way that you would call bind() before listen() in a server. There is nothing more complicated to it than that.

查看更多
等我变得足够好
4楼-- · 2019-02-18 13:10

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));
查看更多
登录 后发表回答