Ethernet client does not connect with local server

Hello everyone,
I am trying to make a simple connection between my Arduino and a local server(using express in nodejs) running on my laptop and both are connected directly, without a router or switch. However it always fails.

I catched the return value from ''client.connect(server, 8080)'' It is always "connection failed".

I've tried a different EthernetSield and cable.

Thanks so much to everyone!

My code:

#include <SPI.h>
#include <Ethernet.h>
// Enter a MAC address and IP address for your controller below.
// The IP address will be dependent on your local network:
byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
IPAddress ip(169,254,188,3); //local ip
IPAddress server(169,254,191,189); //ip where server is running
EthernetClient client;

void setup() {
  Serial.begin(9600);
  Serial.println("Starting...");
  Ethernet.begin(mac,ip);
  if (client.connect(server, 8080)) {
    Serial.println("connected");
  } else {
    Serial.println("connection failed");
  }
  Serial.println(Ethernet.localIP());
}

void loop() {
  if (client.available()) {
    char c = client.read();
    Serial.print(c);
  }
}

does the WebClient example run?

can you ping the Ethernet board from the PC?
make sure your static IP addresses are on the same subnet

I connected an EthernetSheildV1 direct to a Windows 10 PC setting the Win10 Ethernet static IP to 192.168.1.115

ran following program on Arduino Uno with EthernetSheildV1

// TCPcharClient.ino - a simple TCP chat program
// not using DHCP so check subnet address range is correct

#include <Ethernet.h>
#include <SPI.h>

byte mac[] = { 0x90, 0xA2, 0xDA, 0x0E, 0xD0, 0x93 };
// Set the static IP address to use if the DHCP fails to assign
IPAddress ip(192, 168, 1,115);
IPAddress myDns(192, 168, 1,254);   // DNS server

// Initialize the Ethernet client library 
EthernetClient client;

byte server[] = { 192, 168, 1, 10 }; // server IP address
int serverPort=10000;                // server TCP port (open any firewall on server)

void setup() {
  Serial.begin(115200);   // Open serial communications and wait for port to open:
  while (!Serial) ;
  // start the Ethernet connection:
  Serial.println("\n\nInitialize Ethernet (not using DHCP) :");
  Ethernet.begin(mac, ip);
  delay(1000);
  Serial.println(Ethernet.localIP());
  Serial.println("connecting to server...");
  // Ethernet ready, connect to server and transmit data
  if (!client.connect(server, serverPort)) {
     Serial.println("connection failed");
     while(1);
  }
  Serial.println("connection OK");
}

// chat server open
//   transmit text entered at keyboard to server 
//   display text received from server
void loop()
{
  char ch;
  static  String receivedLine = "", transmitLine="";   
  if (client.available())
    if((ch = client.read()) != '\n')
          receivedLine+=ch;                // add to currentline
    else {
          Serial.println("Received '" + receivedLine + "'");
          receivedLine="";
         }
  if(Serial.available())                // if keyboard test available
    if((ch=Serial.read()) != '\n')      // if not new line
         transmitLine+=ch;  // add to currentline
    else  {                               // on \n transmit line
        Serial.println("transmitting '" + transmitLine + "'");
        client.print(transmitLine + "\n");
        transmitLine="";
       }    
}

ran the Java TCPchat server from post #6 on the PC

arduino output

Initialize Ethernet (not using DHCP) :
192.168.1.115
connecting to server...
connection OK
transmitting 'cient test 1'
transmitting '22222222222222222222'
Received 'server test 1
'
Received '22222222222222222
'
Received '
'
transmitting 'client bye'
Received 'server bye
'

the server displayed
direct_connection_test

@Juraj I got the code from ArduinoHttpClient and I used it over the Ethernet library.

var express = require('express');			// include express.js
var app = express();						// a local instance of it
var bodyParser = require('body-parser');	// include body-parser
var WebSocketServer = require('ws').Server	// include Web Socket server

// you need a  body parser:
app.use(bodyParser.urlencoded({extended: false})); // for application/x-www-form-urlencoded

// this runs after the server successfully starts:
function serverStart() {
	var port = server.address().port;
	console.log(server.address());
}

// this is the POST handler:
app.all('/*', function (request, response) {
	console.log('Got a ' + request.method + ' request');
	// the parameters of a GET request are passed in
	// request.body. Pass that to formatResponse()
	// for formatting:
	console.log(request.headers);
	if (request.method == 'GET') {
		console.log(request.query);
	} else {
		console.log(request.body);
	}

	// send the response:
	response.send('OK');
	response.end();
});

// start the server:
var server = app.listen(8080, serverStart);

// create a WebSocket server and attach it to the server
var wss = new WebSocketServer({server: server});

wss.on('connection', function connection(ws) {
	// new connection, add message listener
	ws.on('message', function incoming(message) {
		// received a message
		console.log('received: %s', message);

		// echo it back
		ws.send(message);
	});
});

ip

I ask if the simplest example work to rule out basic problems

@Juraj, only works when the arduino is the service and the node is the client. Follow bellow:

Arduino

#include <SPI.h>
#include <Ethernet.h>
/* ETHERNET VARIABLES */
byte ip[] = {169,254,188,3};
byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
EthernetServer server = EthernetServer(9023);

void setup() 
{
  Serial.begin(9600);
  SPI.begin();
  Ethernet.begin(mac,ip); // init EthernetShield
  delay(1000);
  server.begin();
  if(server.available()){
    Serial.println("Client available");
  } else {
    Serial.println("Client not avaliable");
  }
}

void loop() 
{
  EthernetClient client = server.available();
  server.write("test");
  if (client.available()) {
    receiveResponseFromServer(client);
    String message = client.readStringUntil('\n');
    Serial.println(message);
  }
}

void receiveResponseFromServer(EthernetClient client){
  String message = client.readStringUntil('\n');
  Serial.print("Response -> ");
  Serial.println(message);
}

Node.JS

var net = require('net');

const ip = '169.254.188.3';
const port = 9023;
var client = new net.Socket();

client.connect(port, ip, function () {
  console.log('Connected');
});

client.on('data', function (data) {
  console.log(data); 
  client.write('ok\n');
});

client.on('close', () => {
   client.connect(port, ip);
});
client.on('error', function (err) {
  console.log("Error: " + err.message);
  //client.connect(port, ip);
});

this will only work if you are using a subnet mask like 255.255.0.0
I assume this is uncommon.

Please post the ipconfig of your laptop (=the server) including the subnet mask.
then fit the ip of your Arduino to the IP range of your server (or in other words - only the last IP octet should differ if you have a subnet mask of 255.255.255.0).

try a 500 milliseconds delay between Ethernet.begin(mac,ip); and if (client.connect(server, 8080)) {

@noiasca Follow below:
ipconfig
Thank you!

@Juraj Didn't works :frowning:

try wireshark to monitor traffic on the network

you have to specify the network mask if it is not 255.255.255.0

IPAddress gw(169,254,188,1);
Ethernet.begin(mac, ip, gw, gw, IPAddress(255, 255, 0, 0));`

Niceeeeee @Juraj it works!! :clap: :clap: :clap: :clap:

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.