Skip to content

Commit 0d08dde

Browse files
committed
randomize tcp source port for #1800
1 parent af0bba0 commit 0d08dde

File tree

3 files changed

+12
-3
lines changed

3 files changed

+12
-3
lines changed

shared-module/network/__init__.c

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -99,3 +99,7 @@ void network_module_create_random_mac_address(uint8_t *mac) {
9999
mac[4] = (uint8_t)(rb2 >> 8);
100100
mac[5] = (uint8_t)(rb2);
101101
}
102+
103+
uint16_t network_module_create_random_source_tcp_port(void) {
104+
return 0xc000 | shared_modules_random_getrandbits(14);
105+
}

shared-module/network/__init__.h

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -25,11 +25,12 @@
2525
* THE SOFTWARE.
2626
*/
2727

28-
void network_module_create_random_mac_address(uint8_t *mac);
29-
3028
#ifndef MICROPY_INCLUDED_SHARED_MODULE_NETWORK___INIT___H
3129
#define MICROPY_INCLUDED_SHARED_MODULE_NETWORK___INIT___H
3230

31+
void network_module_create_random_mac_address(uint8_t *mac);
32+
uint16_t network_module_create_random_source_tcp_port(void);
33+
3334
#define MOD_NETWORK_IPADDR_BUF_SIZE (4)
3435

3536
#define MOD_NETWORK_AF_INET (2)

shared-module/wiznet/wiznet5k.c

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -203,8 +203,12 @@ int wiznet5k_socket_accept(mod_network_socket_obj_t *socket, mod_network_socket_
203203
}
204204

205205
int wiznet5k_socket_connect(mod_network_socket_obj_t *socket, byte *ip, mp_uint_t port, int *_errno) {
206+
uint16_t src_port = network_module_create_random_source_tcp_port();
207+
// make sure same outgoing port number can't be in use by two different sockets.
208+
src_port = (src_port & ~(_WIZCHIP_SOCK_NUM_ - 1)) | socket->u_param.fileno;
209+
206210
// use "bind" function to open the socket in client mode
207-
if (wiznet5k_socket_bind(socket, ip, 0, _errno) != 0) {
211+
if (wiznet5k_socket_bind(socket, NULL, src_port, _errno) != 0) {
208212
return -1;
209213
}
210214

0 commit comments

Comments
 (0)