Uno + Ethernet Shield. Problem with Timer1 or receiving data with W5100

Hello, community,

I am trying to use W5100 library directly without using socket library or any higher level libraries to communicate over a tcp connection.

I write a program for Arduino UNO + Ethernet Shield. In my setup I run a TCP Client which connects to a TCP Server and sends one byte of information. Server responds back with one byte of information after connection establishment. I use the Timer1 to measure how long i took for the server to respond after sending packet to the server. I need to use timer for maximal precision (counting ticks), so millis() and micros() not desired.

According to the W5100 Datasheet there are two possibilities to get notified when data arrives from the server.

First: the RECV bit is set in Socket n Interrupt Register.
Second: poll the RX buffer with W5100.getReceivedSize(s); to see if something arrived

To stop my timer I use the first possibility. Please check the code:

	//###########################
		// Establish connection to the server //	
		// Send packet to the server //
	//###########################
	//start timer
	TCNT1 = 0; 
	TIMSK1 |= (1 << TOIE1); 
	
	while((W5100.readSnIR(s) & SnIR::RECV) != SnIR::RECV){}
	
	restTicks = TCNT1; // save rest ticks
	TIMSK1 &= ~(1 << TOIE1); // disable timer1.
	
	if( (bytes_received = W5100.getRXReceivedSize(s)) > 0){
		W5100.recv_data_processing(s, &recvd, 1);
		W5100.execCmdSn(s, Sock_RECV);
		W5100.writeSnIR(s, 0x4);
	}
	else {
		error(3);
	}

After RECV bit was set, I read data from the buffer to empty it, and clear RECV bit afterwards.
The problem is I that when I read the counter register in the restTicks variable, there is only few different values that restTicks takes. I know that due to the noise in the network such discrete values are not possible. So there must be something with the code.

First suspection was optimization. In my project settings optimization is turned off, and restTicks is initially declared as volatile. So the value has to be always updated during the program execution.

I would be very grateful for any thoughts on the subject.
Thanks before hand!

Best regards!